Java Reference
In-Depth Information
example concerns the question of the differences between void, which can only qualify method
return types and has no values, and the object type Void, which has null as its only value—a
question that regularly appears on forums. The special cases of Function such as Supplier<T>,
which could be written () => T in the new notation proposed previously, further attest to the
ramifications caused by the distinction between primitive and object types. We discussed earlier
how reified generics could address many of these issues.
16.2.5. Deeper support for immutability
Some expert readers may have been a little upset when we said that Java 8 has three forms of
values:
Primitive values
(References to) objects
(References to) functions
At one level we're going to stick to our guns and say, “But these are the values that a method
may now take as arguments and return as results.” But we also wish to concede that this is a
little problematic: to what extent do you return a (mathematical) value when you return a
reference to a mutable array? A String or an immutable array clearly is a value , but the case is
far less clear-cut for a mutable object or array—your method may return an array with its
elements in ascending order, but some other code may change one of its elements later.
If we're really interested in functional-style programming in Java, then there needs to be
linguistic support for saying “immutable value.” As noted in chapter 13 , the keyword final
doesn't really achieve this—it only stops the field it qualifies from being updated; consider this:
final int[] arr = {1, 2, 3};
final List<T> list = new ArrayList<>();
The former forbids another assignment arr = ... but doesn't forbid arr[1]=2; the latter forbids
assignments to list but doesn't forbid other methods from changing the number of elements in
list! The keyword final works well for primitive values, but for references to objects, it often
merely gives a false sense of security.
What we're leading up to is this: given that functional-style programming puts a strong
emphasis on not mutating existing structure, there's a strong argument for a keyword such as
transitively_final, which can qualify fields of reference type and which ensures that no
modification can take place to the field nor to any object directly or indirectly accessible via
that field .
 
Search WWH ::




Custom Search