Java Reference
In-Depth Information
Target Typing
Every lambda expression has a type, which is a functional interface type. In other words, a lambda expression
represents an instance of a functional interface. Consider the following lambda expression:
(x, y) -> x + y
What is the type of this lambda expression? In other words, an instance of which functional interface does this
lambda expression represent? We do not know the type of this lambda expression at this point. All we can say about
this lambda expression with confidence is that it takes two parameters named x and y . We cannot tell its return type
as the expression x + y, depending on the type of x and y , may evaluate to a number ( int , long , float , or double )
or a String . This is an implicit lambda expression, and therefore, the compiler will have to infer the types of two
parameters using the context in which the expression is used. This lambda expression may be of different functional
interface types depending on the context in which it is used.
There are two types of expressions in Java:
Standalone Expressions
Poly Expressions
A standalone expression is an expression whose type can be determined by the expression without knowing the
context of its use. The following are examples of standalone expressions:
// The type of expression is String
new String("Hello")
// The type of expression is String (a String literal is also an expression)
"Hello"
// The type of expression is ArrayList<String>
new ArrayList<String>()
A poly expression is an expression that has different types in different contexts. The compiler determines the
type of the expression. The contexts that allow the use of poly expressions are known as poly contexts . All lambda
expressions in Java are poly expressions. You must use it in a context to know its type. Poly expressions existed in Java
prior to Java 8 and lambda expressions. For example, the expression new ArrayList<>() is a poly expression. You
cannot tell its type unless you provide the context of its use. This expression is used in the following two contexts to
represent two different types:
// The type of new ArrayList<>() is ArrayList<Long>
ArrayList<Long> idList = new ArrayList<>();
ArrayList<String> nameList = new ArrayList<>() ;
The compiler infers the type of a lambda expression. The context in which a lambda expression is used expects
a type, which is called the target type . The process of inferring the type of a lambda expression from the context is
known as target typing . Consider the following pseudo code for an assignment statement where a variable of type T is
assigned a lambda expression:
T t = <LambdaExpression>;
 
Search WWH ::




Custom Search