java boilerplate

Thursday, December 01, 2005

'Function' interfaces.

When one needs to pass a function as an argument, you need to go through a rather convoluted anonymous inner class definition, which tends to get a bit overly wordy:
     Collections.sort(names, new Comparator<String>() {
public int compare(String a, String b) {
return 0; //Some sort of comparison algorithm.
}
});


Yet, the compile-time checking enforced by, amongst other things, the structure of the 'Comparator' interface and the generics features of 'Comparator', is clearly something that should be kept if possible. We propose the notion of a 'function' interface. Our example code now changes to:
     Collections.sort(names, Comparator<String>(String a, String b) {
return 0; //Some sort of comparison algorithm.
});


The definition of Comparator must also change to reflect that it can be used as a function interface:

     public @Function interface Comparator<T> {
int compare(T o1, T o2);
}


The 'Function' annotation is a marker annotation (has no fields). It's only valid on interfaces. The interface must have only one method (mentioning some methods that Object already has in order to explain some particulars in the javadoc is allowed).

BACKWARDS COMPATIBILITY: No problems here. No new keywords are neccessary. All existing 'function interfaces', such as Comparator and Iterable can be refitted with @Function markers.

0 Comments:

Post a Comment

<< Home