Why closures are useful
Via the Fishbowl we get an explanation of why closures are useful, and why you won't see them in Java:
The advantage of closures is that they allow you to add new control structures to your language. Java 1.5 is looking to introduce a foreach construct to iterate over lists. With closures, such language constructs become unnecessary (Ruby has only very primitive native looping constructs) because you can define your own. Similarly, closures allow you to dispense with boiler-plate wrapping code such as we see everywhere with file or database manipulation in Java.
That's part of the reason Smalltalk is so much more productive than Java - mor expressive power. Why won't you see it in Java? Charles explains:
You can approximate the functionality of closures in Java using anonymous inner classes. There are two problems with this, though. Firstly, anonymous inner classes are unnecessarily verbose. Closures are supposed to be a short-cut, and anonymous inner-classes are anything but. This can be got around by adding some syntactic sugar to the language of course, but the use of classes is still quite heavy-weight. (Each anonymous inner class is an additional compilation unit, for example)The bigger problem is that anonymous inner classes in Java don't really close over their surrounding scope - they cheat. The best way to demonstrate this by example is this:
i = 1; 1.upto(100) { |num| i *= num; } puts i;The above code prints out the factorial of 100. As you can see, the variable i is modified inside the closure, but because the closure is executed in the surrounding scope, its value is changed afterwards. This is unlike the behaviour of a regular function call, where variable values in surrounding scopes are not changed.
If you tried to write the equivalent code in Java, it wouldn't compile. Java doesn't really close over the surrounding scope, it copies it. To hide this implementation detail, any variable referenced inside the inner class must be declared final outside it: which is fine if your inner class is manipulating a mutable reference type like a list, but breaks if you want to work with immutable reference types, or value types. (i.e. Strings and numbers)
This is why you're unlikely to see closures in Java, sadly. To implement them properly would involve making changes to some pretty fundamental parts of the JVM. It's a pity, though, because they're damn useful
It's a pretty good read - gives examples in Ruby, which is explicitly modeled on Smalltalk.

