Monday, August 9, 2010

Hacking closure in Java 7.0 (3): Target Type Selection

I spent some times yesterday and today to play around with the closure prototype right from the source. First, I reinstalled the binary jdk 7 to the build 103 one and then get the langtools project from mercury. Finally, I built the project and got my javac that can compile closure. 

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: