Re:Java finally getting closures, method handles and traits ...
by skybrian on Sunday January 23, 2011 @04:58PM
(#2133447)
While it's true that anonymous inner classes implement a form of closures, among the folks talking about the next version of Java, "closures" has become the shorthand for the various proposals to improve the syntax for callbacks and/or add true anonymous functions.
Re:Java finally getting closures, method handles and traits ...
by dcminter on Sunday January 23, 2011 @07:47PM
(#2133813)
Do you mean method local variables? Because if so it doesn't - it copies them and only allows you to reference them if they're declared final (const) for exactly that reason.
Re:Java finally getting closures, method handles and traits ...
by SeanLuke on Sunday January 23, 2011 @09:59PM
(#2134072)
There's a hack. Instead of declaring a local variable like "final double d = 4;", you can declare it "final double[] d = new double[] { 4 };" Then you can freely modify the 4 to something else inside the anonymous class. Why Sun didn't just bake that into the compiler instead of requiring a hack is beyond me.
Re:Java finally getting closures, method handles and traits ...
by colanderman on Sunday January 23, 2011 @08:07PM
(#2133863)
That's exactly what a closure is.
Keep in mind that the concept of a closure has been bred in the functional programming community, where variables aren't mutable.
If you really need to reference a mutable variable in the enclosing scope, you can do in Java exactly what you can do in languages like ML/Scheme -- let the variable reference a mutable box (in Java, an object). The reference to the box (or object) is copied, not the box itself.
In fact, in Java you can go one step further and just reference the entire enclosing scope by storing the parent's "this" in a final variable.
Re:Java finally getting closures, method handles and traits ...
by DennisP on Monday January 24, 2011 @09:43AM
(#2135248)
Scheme has mutable variables, and introduced lexical closures in the 70's. You don't need any tricks with mutable boxes, you can just update an integer in the outer scope and it works fine. Scheme doesn't have an object system built in, but the closures make it easy to roll your own.
I suspect the author is confusing closures (a language implementation technique) with anonymous functions (a language feature which can be implemented using closures).