Syntax of closure
In forum (fora) and blogs, i have often seen that closures are compared to anonymous classes in order to reject the proposed syntax of closure. In this entry, i try to show up why the closure syntax is such as it is by explaining the differences with the anonymous class syntax.
Let me introduce an example that sort a list of integers in reverse order. There are two codes, one written with an anonymous class and the other written with a closure using the closure convertion.
The code using a closure:
List<Integer> list=Arrays.asList(666,7,12);
Collections.sort(list,int(Integer i1,Integer i2) {
if (i1<i2)
return 1;
else
if (i2<i1)
return -1;
return 0;
});
And the code using an anonymous class:
List<Integer> list=Arrays.asList(666,7,12);
Collections.sort(list,new Comparator<Integer>(){
public int compareTo(Integer i1,Integer i2) {
if (i1<i2)
return 1;
else
if (i2<i1)
return -1;
return 0;
}
});
I've found five differences and all have a reason so i don't see why people want to change the proposed syntax.
A step by step comparison
- An anonymous class starts with new, because it always create a new object, closure can reuse the same singleton so no "new".
- an anonymous class takes a type (a class, an abstract class or an interface), closure doesn't need to specify a type because the compiler infers the type. Due to an implementation detail, closure convertion can only occur with an interface.
- an anonymous class must parameterize its constructor (Comparator<Integer>). Closure can infer the value of the type variable. Because of the backward compatibility of generics, the compiler must be able to distinguish a raw type from a parametrized type so the type variable of an anonymous class can't be infered.
- an anonymous class can take arguments, a closure can't because as state above, a closure can only implements an interface.
- an anonymous class need to specify access modifier (public) and the method name. The closure have only one public method so it's neither necessary to name it nor to specify a modifier.
I hope this entry will reconcile the grimpies with the proposed
syntax.
Wow, this is my fourth entry about closure,
it's time for me to register with CA (Closure Anonymous) :)
- Login or register to post comments
- Printer-friendly version
- forax's blog
- 645 reads





