back

by dcminter·15y ago·view on hn ↗
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.
2 comments
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.
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.

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.