Tuesday, December 26, 2006

Closures in Java

I hit upon closures first (well at least I thought so until I knew what they were and realized that I had used them before) when coding in Ruby. Closures are blocks of code that can be passed as arguments to other methods. In this sense they are similar to function pointers in C. But closures are a tad more powerful in that they also extend the scope of variables in the lexical scope of where they are used. Refer http://www.eclipsezone.com/eclipse/forums/t86911.html for a precise definition.

I recently completed a project involving Ruby on Rails. Having worked with Java for the last three years, I could not help but compare it with Java. I was wondering if any of the language and framework features could be implemented in Java and the numerous frameworks based on it. Blocks and closures are impressive language constructs that allow customization and extension of other language constructs (like the looping constructs) and APIs.

Gafter, Gosling et al's proposal to add closures in Java seems to be a good bet. This would put an end to the addition of more new statements like 'for each' that was added in J2SE 5.0.

Am keeping an eye on the numerous forums and blogs abuzz with discussions on Java and Ruby. It's interesting how Ruby and more importantly the Rails framework is causing so much flutter.

Pointer:
http://www.javac.info/closures-v04.html

-Ashish.