Neal Gafter gave a great
talk on closures at BeJUG this year. While I’ve not be in favor of Generics and Autoboxing I must say that Closures seems like they should have been in the language from the get go.
One of the problems with closures is getting things to work normally. Anonymous inner-classes don’t get it quite right. You can see this with the forced use of final.
Using final allows the compiler to hoist variables to that they can be visible to the inner-class. It’s a hack around the variable visibility and binding rules that are at the core of how Java is built.
The other problem with Anonymous inner-classes is with the keyword "this". It is coerced into working in AIC but….... In Neal’s talk he stresses that getting “this” and other visibility rules right is important. The big wins are seen with listeners and maybe, just maybe we can rid ourselves of iterators all together. Here is the example Neal gives of a new control structure that is really a method call;
with(InputStream s : expression) {
// operate on the stream
}This is a great example (something that we did in Smalltalk all the time) of how to create a block of code that was guaranteed to close a stream without try-catch-finally blocks.
There is so much more in this presentation that you may need to watch it more than once. There is more information at
Neils blogtags: closures gafter java