I\'m reading a chapter on lambdas in Herbert Schildt\'s \"Java: The Complete Reference\" and there are quite a few references to \"lambda target type\" and \"target type context
You should understand "target type" as the functional interface as which the function is (intended to be) used.
Think about this: what is this lambda expression expected to be and how can it be used?
() -> "123";
As the book notes it, this expression can't be used on its own. It needs to be associated with a functional interface.
Now, what functional interface can be the type of a lambda expression is picked up from the context. This is where the "target type" of the lambda expression means something.
Consider these examples:
Example 1:
void printString(Supplier<String> supplier) {
System.out.println(supplier.get());
}
You can call that with
printString(() -> "123");
In this case, you mean the type of () -> "123"
to be Supplier<String>
. That's the target type of () -> "123"
in this context.
Example 2:
MyInterface<String> myInt = () -> "123";
As you can see, an identical lambda expression was used, but its target type is now MyInterface<String>
.
Likewise, you can declare another functional interface that has the same signature as MyInterface.func()
and assign the very same lambda expression to it. The target type changes in these varied contexts.
One of the definitions of "target" (taken from here) is:
a result or situation that you intend to achieve.
You can say the result a lambda expression intends to achieve is to implement some functional interface. Hence that functional interface can be seen as the target of that lambda expression, and the type of the functional interface is the target type.
Hence the target type is the type of the functional interface implemented by the lambda expression.
The target type can be inferred based on the context in which the lambda expression is used:
In
(int n) -> n % 2 == 0
the target type is unknown. If you assign this expression to some functional interface reference, that would be the target type.
In
MyInterface<String> myInt = () -> { return "123"; }
the target type is MyInterface<String>
.