BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Closures Proposed for Java SE 7

Closures Proposed for Java SE 7

Bookmarks
Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé (some of the main architects of the Java language) on Friday put out a proposal for adding closures and local functions to Java SE 7, a feature that Smalltalk users always raved about, which is common in scripting langauges and even C# supports them. 
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:
void(int) totalizer = (int i) : total = total + i;
totalizer(1);
totalizer(2);
System.out.println(total); // Prints 3
int total=0;

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;
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.

Rate this Article

Adoption
Style

BT