Java Reference
In-Depth Information
The compiler now verifies the compatibility of the returned value from the lambda expression and the return type
of the add() method. The return type of the add() method is double . The lambda expression returns x + y , which
would be of a double as the compiler already knows that the types of x and y are double . The lambda expression does
not throw any checked exceptions. Therefore, the compiler does not have to verify anything for that. At this point, the
compiler infers that the type of the lambda expression is the type Adder .
Apply the rules of target typing for the following assignment statement:
Joiner joiner = (x, y) -> x + y;
This time, the compiler infers the type for the lambda expression as Joiner . Do you see an example of a poly
expression where the same lambda expression (x, y) -> x + y is of the type Adder in one context and of the type
Joiner in another.
Listing 5-3 shows how to use these lambda expressions in a program. Note that it's business as usual after you use
a lambda expression to create an instance of a functional interface. That is, after you create an instance of a functional
interface, you use the instance as you used before Java 8. The lambda expression does not change the way the instance
of a functional interface is used to invoke its method.
Listing 5-3. Examples of Using Lambda Expressions
// TargetTypeTest.java
package com.jdojo.lambda;
public class TargetTypeTest {
public static void main(String[] args) {
// Creates an Adder using a lambda expression
Adder adder = (x, y) -> x + y;
// Creates a Joiner using a lambda expression
Joiner joiner = (x, y) -> x + y;
// Adds two doubles
double sum1 = adder.add(10.34, 89.11);
// Adds two ints
double sum2 = adder.add(10, 89);
// Joins two strings
String str = joiner.join("Hello", " lambda");
System.out.println("sum1 = " + sum1);
System.out.println("sum2 = " + sum2);
System.out.println("str = " + str);
}
}
sum1 = 99.45
sum2 = 99.0
str = Hello lambda
I will now discuss the target typing in the context of method calls. You can pass lambda expressions as arguments
to methods. Consider the code for class LambdaUtil shown in Listing 5-4.
 
Search WWH ::




Custom Search