There is alot of debate going on between the CICE and BGGA proposals for Java closure support.
I thought I would try to experiment with the different proposals and compare to languages I am using right now. I picked something simple to try out, like summing an array of integers:
Also check out good closures, bad closures.
Actionscript 3
Assume you have a reduce function, for example:
public function reduce(array:Array, f:Function, index:int = 0):* {
if (index == array.length - 1) return array[index];
return f(array[index], reduce(array, f, index + 1));
}
Then the syntax is:
var array:Array = [ 1, 2, 3 ];
reduce(array, function(x1:Number, x2:Number):Number { return x1 + x2; });
Ruby
Sorry I have to.
array = [ 1, 2, 3 ];
array.inject { |sum, n| sum + n }
or with Symbol#to_proc:
array = [ 1, 2, 3 ]; array.inject(&:+)
Java (CICE)
Assume you have a “Reducer” interface (and Collections#reduce):
interface Reducer {
T reduce(T t1, T t2);
}
List = Arrays.asList([ 1, 2, 3 ]);
Integer sum = Collections.reduce(list, Reducer(Integer x1, Integer x2) {
return x1 + x2;
});
I think this is right, help? So you might have to declare new interfaces if the API doesn’t have them. It would probably have common ones though.
Java (BGGA)
Assume you have Collections#reduce:
List = Arrays.asList([ 1, 2, 3 ]);
Integer sum = Collections.reduce(list, { Integer x, Integer y => x+y });
The other powerful thing with the BGGA proposal is the control invocations, like:
Lock lock = new Lock();
Lock.withLock(lock) {
doSomething();
}
// Automatically close stream when done
with(FileInputStream f : exp) {
doSomething();
}
Like in Ruby:
mutex = Mutex.new
mutex.synchronize do
doSomething
end
File.open("foo.txt", "w") do |file|
doSomething
end
Since I’ve been doing Ruby lately, I know which Java proposal I prefer. The CICE doesn’t address the problem that within an anonymous inner instance return, and this and any anonymous instance methods are scoped to that anonymous instance and not the enclosing method.
I guess CICE is more about reducing the verbosity of the anonymous instance declaration and allowing mutability on public variables, and its not a real closure in the strict definition. I know people refer to anonymous inner classes as the poor man’s closure, but I don’t really think of it as a closure, I think of it as, you know, an anonymous inner class.


