Java Reference
In-Depth Information
In the same way that Java 7 allowed you to leave out the generic types for a constructor, Java
8 allows you to leave out the types for whole parameters of lambda expressions. Again, it's
not magic: javac looks for information close to your lambda expression and uses this in-
formation to figure out what the correct type should be. It's still type checked and provides
all the safety that you're used to, but you don't have to state the types explicitly. This is what
we mean by type inference .
NOTE
It's also worth noting that in Java 8 the type inference has been improved. The earlier ex-
ample of passing new HashMap<>() into a useHashmap method actually wouldn't have
compiled in Java 7, even though the compiler had all the information it needed to figure
things out.
Let's go into a little more detail on this point with some examples.
In both of these cases we're assigning the variables to a functional interface, so it's easier to
see what's going on. The first example ( Example 2-11 ) is a lambda that tells you whether an
Integer is greater than 5. This is actually a Predicate —a functional interface that checks
whether something is true or false.
Example 2-11. Type inference
Predicate < Integer > atLeast5 = x -> x > 5 ;
A Predicate is also a lambda expression that returns a value, unlike the previous Ac-
tionListener examples. In this case we've used an expression, x > 5 , as the body of the
lambda expression. When that happens, the return value of the lambda expression is the
value its body evaluates to.
You can see from Example 2-12 that Predicate has a single generic type; here we've used
an Integer . The only argument of the lambda expression implementing Predicate is there-
fore inferred as an Integer . javac can also check whether the return value is a boolean , as
that is the return type of the Predicate method (see Figure 2-2 ).
Example 2-12. The predicate interface in code, generating a boolean from an Object
public
public interface
interface Predicate
Predicate < T > {
boolean
boolean test ( T t );
}
Search WWH ::




Custom Search