For programming in the small, closures allow one to abstract an algorithm over a piece of code; that is, they allow one to more easily extract the common parts of two almost-identical pieces of code. For programming in the large, closures support APIs that express an algorithm abstracted over some computational aspect of the algorithm. We propose to add function types and closures to Java. We anticipate that the additional expressiveness of the language will simplify the use of existing APIs and enable new kinds of APIs that are currently too awkward to express using the best current idiom: interfaces and anonymous classes.Peter commented further on how anonymous classes aren't good enough to simulate closures. Gilad Bracha blogged a bit about why the proposal is coming now, saying that "the widespread adoption of scripting languages has exposed a lot of people to the idea of first class functions. It has also shown that another argument used against closures - that they are too abstract for ordinary programmers - is just as imbecilic as the one about customer demand."
DWR founder Joe Walker also wrote about how the Collections classes would need to be modified to support closures:
Javalobby posted a link to the proposal on Friday which drew a large discussion of developers mostly supportive of the idea. Neal Gafter on saturday wrote a detailed justification of the benefit of closures, showing a set of code samples and how closures simplified them significantly. Neal's conclusion: closures "allow you to easily abstract away aspects of code that would otherwise require complex contortions.void(int) totalizer = (int i) : total = total + i;int total=0;
totalizer(1);
totalizer(2);
System.out.println(total); // Prints 3
But what you really want is to be able to do things like this:
int[] numbers = new int[] { 100, 200 };
numbers.each(totalizer);
System.out.println(total); // Now prints 303;