4 ms·
Java has had closures for years. Otherwise how would an anonymous inner class reference its parent's local variables? I suspect the author is confusing closur
by colanderman 16y ago
Java has had closures for years. Otherwise how would an anonymous inner class reference its parent's local variables?
I suspect the author is confusing closures (a language implementation technique) with anonymous functions (a language feature which can be implemented using closures).
- stevoski 16y agoJava has had this since Java 1.1, I believe.
- skybrian 16y agoWhile 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.
- dcminter 16y agoDo 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.
- colanderman 16y agoThat'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.
- DennisP 16y agoScheme 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.
- SeanLuke 16y agoThere'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.
- deleted 16y ago[deleted]