Java 1.7 Gets Closures?

, Aug 19, 2006

Closures in Java! Here’s the proposal (PDF, authored by Gilad Bracha, Neal Gafter, James Gosling, Peter von der Ahé. Neal Gafter has an abbreviated HTML version), including some comments.

Local functions, as first class objects:

    public static void main(String[] args) {
int plus2(int x) { return x+2; }
int(int) plus2b = plus2;
System.out.println(plus2b(2));
}

Rewritten using a closure:

     int(int) plus2b = (int x) {return x+2; };

One highlight:

Names that are in scope where a function or closure is defined may be referenced within the closure. We do not propose a rule that requires referenced variables be final, as is currently required for anonymous class instances. The constraint on anonymous class instances is also relaxed to allow them to reference any local variable in scope.

Very cool — too sad it’ll take years until it’s available, and even longer for it to become widespread enough to be used in practice.

Update: More about this from Gilad Bracha, Peter von der Ahé.

Another update: Excellent discussion at Lambda the Ultimate.