Домой United States USA — software New JEP Would Simplify Java Type Variance

New JEP Would Simplify Java Type Variance

131
0
ПОДЕЛИТЬСЯ

NewsHubA new JEP Candidate proposes to facilitate the handling of the recondite concept of type variance in Java. The new proposal, potentially targeting Java 10, would introduce a means for specifying default variance of target types in the definition of the generic type, as opposed to the current style of indicating it through wildcards when the generic type is instantiated. This proposal is not a replacement for wildcards, but rather a way to reduce the need for them.
The topic of type variance is still rather obscure for many developers, and the fact that in Java this problem was addressed through some rather unpopular wildcards didn’t help to make it clearer. For this reason, and to make sure our readers understand the potential impact of this JEP, in this article we will first explain what type variance is and how it is currently addressed in Java, followed by a description of what the new proposal would achieve.
Consider the following code belonging to a typical online shopping application:
If we have a method scan(Product product) , and we call it passing a FrozenProduct object, the call works with no problem; this is well-known under the common rules of polymorphism. However, when the arguments include generics, the same logic cannot be applied, and the following code would fail to compile:
When generics are used in Java, no assumptions are made with regards to the compatibility of the target type in relation to its subtypes or supertypes. In other words, when generics are used, we say that the target type is by default invariant : only the exact type is accepted.
In our example above however, we can see that the addAllProducts method would actually work with a List of Product or of any its subtypes. When a generic argument can accept either its target type or any of its subtypes, we say that the type is covariant , which in Java is expressed using extends :
In these examples, the variance of the target type that is accpeted is the subtype.

Continue reading...