Java Reference
In-Depth Information
The target type of the lambda expression in this context is
T
. The compiler uses the following rules to determine
whether the
<LambdaExpression>
is assignment compatible with its target type
T
:
•
T
must be a functional interface type.
The lambda expression has the same number and type of parameters as the abstract method
•
of
T
. For an implicit lambda expression, the compiler will infer the types of parameters from
the abstract method of
T
.
The type of the returned value from the body of the lambda expression is assignment
•
compatible to the return type of the abstract method of
T
.
If the body of the lambda expression throws any checked exceptions, those exceptions must
•
be compatible with the declared
throws
clause of the abstract method of
T
. It is a compile-time
error to throw checked exceptions from the body of a lambda expression, if its target type's
method does not contain a
throws
clause.
Let's look at few examples of target typing. Consider two functional interfaces,
Adder
and
Joiner
, as shown in
Listing 5-1 and Listing 5-2, respectively.
Listing 5-1.
A Functional Interface Named Adder
// Adder.java
package com.jdojo.lambda;
@FunctionalInterface
public interface Adder {
double add(double n1, double n2);
}
Listing 5-2.
A Functional Interface Named Joiner
// Joiner.java
package com.jdojo.lambda;
@FunctionalInterface
public interface Joiner {
String join(String s1, String s2);
}
The
add()
method of the
Adder
interface adds two numbers. The
join()
method of the
Joiner
interface
concatenates two strings. Both interfaces are used for trivial purposes; however, they will serve the purpose of
demonstrating the target typing for lambda expressions very well.
Consider the following assignment statement:
Adder adder = (x, y) -> x + y;
The type of the
adder
variable is
Adder
. The lambda expression is assigned to the variable
adder
, and therefore,
the target type of the lambda expression is
Adder
. The compiler verifies that
Adder
is a functional interface. The
lambda expression is an implicit lambda expression. The compiler finds that the
Adder
interface contains a
double
add(double, double)
abstract method. It infers the types for
x
and
y
parameters as
double
and
double
, respectively.
At this point, the compiler treats the statement as shown:
Adder adder = (double x, double y) -> x + y;