Java Reference
In-Depth Information
Special void-compatibility rule
If a lambda has a statement expression as its body, it's compatible with a function descriptor
that returns void (provided the parameter list is compatible too). For example, both of the
following lines are legal even though the method add of a List returns a boolean and not void as
expected in the Consumer context (T -> void):
// Predicate has a boolean return
Predicate<String> p = s -> list.add(s);
// Consumer has a void return
Consumer<String> b = s -> list.add(s);
By now you should have a good understanding of when and where you're allowed to use lambda
expressions. They can get their target type from an assignment context, method invocation
context (parameters and return), and a cast context. To check your knowledge, try Quiz 3.5 .
Quiz 3.5: Type checking-why won't the following code compile?
How could you fix the problem?
Object o = () -> {System.out.println("Tricky example"); };
Answer:
The context of the lambda expression is Object (the target type). But Object isn't a functional
interface. To fix this you can change the target type to Runnable, which represents a function
descriptor () -> void:
Runnable r = () -> {System.out.println("Tricky example"); };
You've seen how the target type can be used to check whether a lambda can be used in a
particular context. It can also be used to do something slightly different: infer the types of the
parameters of a lambda.
Search WWH ::




Custom Search