Java Reference
In-Depth Information
16.2.2. Type system enhancements
We discuss two possible enhancements to Java type's system: declaration-site variance and
local variable type inference .
Declaration-site variance
Java supports wildcards as a flexible mechanism to allow subtyping for generics (more generally
referred to as use-site variance). This is why the following assignment is valid:
List<? extends Number> numbers = new ArrayList<Integer>();
But the following assignment, omitting the ? extends, gives a compile-time error:
Many programming languages such as C# and Scala support a different variance mechanism
called declaration-site variance. They allow programmers to specify variance when defining a
generic class. This feature is useful for classes that are inherently variant. Iterator, for example,
is inherently covariant and Comparator is inherently contravariant. You shouldn't need to think
in terms of ? extends or ? super when you use them. This is why adding declaration-site variance
to Java would be useful because these specifications instead appear at the declaration of classes.
As a result, it would reduce some cognitive overhead for programmers. Note that at the time of
this writing (June 2014) there's a proposal investigating declaration-site variance for Java 9. [ 2 ]
2 See https://bugs.openjdk.java.net/browse/JDK-8043488 .
More type inference
Originally in Java, whenever we introduced a variable or method, we gave its type at the same
time. For example,
double convertUSDToGBP(double money) { ExchangeRate e = ...; }
contains three types; these give the result type of convertUSDToGBP, the type of its argument
money, and the type of its local variable e. Over time this has been relaxed in two ways. First,
you may omit type parameters of generics in an expression when the context determines them.
For example,
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
 
Search WWH ::




Custom Search