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<String> 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<String>
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…