Java Reference
In-Depth Information
The program in Listing 5-7 is similar to the one shown in Listing 5-5, except that it uses the LambdaUtil2 class.
It uses explicit lambda expressions and a cast to resolve the ambiguous match for lambda expressions.
Listing 5-7. Resolving Ambiguity During Target Typing
// LambdaUtil2Test.java
package com.jdojo.lambda;
public class LambdaUtil2Test {
public static void main(String[] args) {
LambdaUtil2 util = new LambdaUtil2();
// Calls the testAdder() method
util.test((double x, double y) -> x + y);
// Calls the testJoiner() method
util.test((String x, String y) -> x + y);
// Calls the testJoiner() method. The Joiner will
// add a space between the two strings
util.test((Joiner)(x, y) -> x + " " + y);
// Calls the testJoiner() method. The Joiner will
// reverse the strings and join resulting strings in
// reverse order adding a comma in between
util.test((Joiner)(x, y) -> {
StringBuilder sbx = new StringBuilder(x);
StringBuilder sby = new StringBuilder(y);
sby.reverse().append(",").append(sbx.reverse());
return sby.toString();
});
}
}
Using an Adder:190.9 + 8.5 = 199.4
Using a Joiner:"Hello" + "World" = "HelloWorld"
Using a Joiner:"Hello" + "World" = "Hello World"
Using a Joiner:"Hello" + "World" = "dlroW,olleH"
Lambda expressions can be used only in the following contexts:
Assignment Context : A lambda expression may appear to the right-hand side of the assignment
operator in an assignment statement. For example,
ReferenceType variable1 = LambdaExpression;
Method Invocation Context : A lambda expression may appear as an argument to a method or
constructor call. For example,
util.testJoiner(LambdaExpression);
 
Search WWH ::




Custom Search