Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: