We have seen in previous posts (008 - Hacking closure in Java 7.0 (2): Capturing local variable and instance and 007 - Hacking closure in Java 7.0 (1): SAM Conversion ) that closure can be used to convert SAM. From the context of the code, the compiler infers which class it should create from the lambda. Now, this is OK when there is one interface that matches the lambda. For example, the method apply of ListUtil accepts two null-ary interfaces, Constant and Tester that have the following codes:
public interface Constant<T> {
T get();
}
public interface Tester<T> {
T test();
}
class ListUtil {
...
static void apply(Constant<T> c) { ... }
static void apply(Tester<T> t) { ...}
}
The call ListUtil.apply( #() { 5 }) is ambigous, because it matches two apply methods above. To disambiguate the call, an explicit target type needs to be selected. This can be done as follow:
ListUtil.apply(Constant<Integer> #() { 5 })
which explicitly tells the complier to use the apply(Constant<T> ) version of the overloaded method.
But...
I would have prefered not to overload, it's better to have method with different name than overload it.
No comments:
Post a Comment