While reading the article Target Typing and I'm getting a bit confused with the following paragraph:
ActionListener l = (ActionEvent e) -> ui.dazzle(e.getModifiers());
An implication of this approach is that the same lambda expression can
have different types in different contexts:
Callable c = () -> "done";
PrivilegedAction a = () -> "done";
In the first case, the lambda expression () -> "done" represents an
instance of Callable. In the second case, the same expression
represents an instance of PrivilegedAction.
The compiler is responsible for inferring the type of each lambda
expression. It uses the type expected in the context in which the
expression appears; this type is called the target type. A lambda
expression can only appear in a context whose target type is a
functional interface.
Can you explain me these points in relation with the quoted paragraph in a simple way:
target type
context
I will really appreciate it if you also provide code snippets.
解决方案
Context
Context is the way an expression is used within the code. It's not just lambda expressions - it's any expression, like a+b, a++ or Math.random().
Examples of possible contexts:
Assignment: take the expression a+b. If you assign it to a variable, it is used in an assignment context:
c = a+b;
Argument to a method or constructor:. This is when you pass it to some method call:
System.out.println(a+b);
Return value: When you are using the expression in a return statement:
return a+b;
Index to an array: When your expression is the index of an array:
x[a+b] = 3;
Target type
The target type is the type expected in the given context. For example, if you have a method defined as:
public int myMethod() { ... }
then any expression in a return statement in its body is expected to have the type int. So if you have this:
return a+b;
inside myMethod, it's expected that a+b will resolve to an int or something that's assignable to an int.
Now, suppose you have this method:
public void anotherMethod( double d );
Then when you call it, and pass an expression as an argument, that expression is expected to be of type double. So a call like:
anotherMethod(a+b);
expects a+b to resolve to a double. That's its target type.
In your example
In the declaration:
Callable c = () -> "done";
the expression is the lambda expression () -> "done". It is used in an assignment context (it is assigned to c). And the target type is Callable because that's what is expected when you assign anything to c.
For a more formal discussion, refer to the Java Language Specification, Chapter 5.