17.9 Lambdas: A Deeper Look
Type Inference and a Lambda’s Target Type
Lambda expressions can be used anywhere functional interfaces are expected. The Java compiler can usually infer the types of a lambda’s parameters and the type returned by a lambda from the context in which the lambda is used. This is determined by the lambda’s target type—the functional-interface type that’s expected where the lambda appears in the code. For example, in the call to IntStream
method map
from stream pipeline in Fig. 17.4
IntStream.rangeClosed(1, 10)
.map((int x) -> {return x * 2;})
.sum()
the target type is IntUnaryOperator
, which represents a method that takes one int
parameter and returns an int
result. In this case, the lambda parameter’s type is explicitly ...
Get Java How To Program, Late Objects, 11th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.