Java Reference
In-Depth Information
public void test(Joiner joiner) {
String s1 = "Hello";
String s2 = "World";
String s3 = joiner.join(s1,s2);
System.out.print("Using a Joiner:");
System.out.println("\"" + s1 + "\" + \"" + s2 + "\" = \"" + s3 + "\"");;
}
}
Consider the following snippet of code:
LambdaUtil2 util = new LambdaUtil2();
util.test((x, y) -> x + y); // A compile-time error
The second statement results in the following compile-time error:
Reference to test is ambiguous. Both method test(Adder) in LambdaUtil2 and method test(Joiner) in
LambdaUtil2 match.
The call to the test() method fails because the lambda expression is implicit and it matches both versions of the
test() method. The compiler does not know which method to use: test(Adder adder) or test(Joiner joiner) . In
such circumstances, you need to help the compiler by providing some more information. The following are the some
of the ways to help the compiler resolve the ambiguity:
If the lambda expression is implicit, make it explicit by specifying the type of the parameters.
Use a cast.
Do not use the lambda expression directly as the method argument. First, assign it to a
variable of the desired type, and then, pass the variable to the method.
Let's discuss all three methods to resolve the compile-time error. The following snippet of code changes the
lambda expression to an explicit lambda expression:
LambdaUtil2 util = new LambdaUtil2();
util.test((double x, double y) -> x + y); // OK. Will call test(Adder adder)
Specifying the type of parameters in the lambda expression resolved the issue. The compiler has two candidate
methods: test(Adder adder) and test(Joiner joiner) . With the (double x, double y) parameter information, only
the test(Adder adder) method matches.
The following snippet of code uses a cast to cast the lambda expression to the type Adder :
LambdaUtil2 util = new LambdaUtil2();
util.test((Adder)(x, y) -> x + y); // OK. Will call test(Adder adder)
Using a cast tells the compiler that the type of the lambda expression is Adder , and therefore, helps it choose the
test(Adder adder) method.
Consider the following snippet of code that breaks down the method call into two statements:
LambdaUtil2 util = new LambdaUtil2();
Adder adder = (x, y) -> x + y;
util.test(adder); // OK. Will call test(Adder adder)
The lambda expression is assigned to a variable of type Adder and the variable is passed to the test() method.
Again, it helps the compiler choose the test(Adder adder) method based on the compile-time type of the adder
variable.
Search WWH ::




Custom Search