Java Reference
In-Depth Information
can be abbreviated to the following since Java 7:
Map<String, List<String>> myMap = new HashMap<>();
Second, using the same idea—propagating the type determined by context into an expression—a
lambda expression such as
Function<Integer, Boolean> p = (Integer x) -> booleanExpression;
can be shortened to
Function<Integer, Boolean> p = x -> booleanExpression;
by omitting types. In both cases the compiler infers the omitted types.
Type inference gives a few advantages when a type consists of a single identifier, the main one
being reduced editing work when replacing one type with another. But as types grow in size,
generics parameterized by further generic types, then type inference can aid readability. [ 3 ] The
Scala and C# languages permit a type in a local-variable-initialized declaration to be replaced
with the keyword var, and the compiler fills in the appropriate type from the right side. For
example, the declaration of myMap shown previously using Java syntax could be rendered like
this:
3 Of course, it's important that type inference be done sensibly. Type inference works best when
there's only one way, or one easily documentable way, to re-create the type the user has omitted.
It's a source of problems if the system infers a different type from the one the user was thinking
of; so a good design of type inference will give a fault when there are two different incomparable
types that could be inferred instead of appearing just to pick the wrong one seemingly at
random.
var myMap = new HashMap<String, List<String>>();
This idea is called local variable type inference ; you can expect similar developments in Java
because they decrease clutter caused by redundant type repetition.
There's some small cause for concern, however; given a class Car that subclasses a class Vehicle
and then does the declaration
var x = new Vehicle();
 
Search WWH ::




Custom Search