Guy Steele on variables-captured-by-anon-must-be-final (closures)
# 2003-08-22 08:45:08 -0400 | Java | 4 CommentsThere have been some intersting comments by Guy Steele on the ll1 maillist regarding design decisions in Java. Tidbits follow.
You know how local variables or arguments that are “captured” by an inner class need to be declared final? Well, it originally wasn’t going to be that way. We would have had “closures”:
Guy Steele wrote: Actually, the prototype implementation *did* allow non-final variables to be referenced from within inner classes. There was an outcry from *users*, complaining that they did not want this! The reason was interesting: in order to support such variables, it was necessary to heap-allocate them, and (at that time, at least) the average Java programmer was still pretty skittish about heap allocation and garbage collection and all that. They disapproved of the language performing heap allocation "under the table" when there was no occurrence of the "new" keyword in sight. Maybe we could lift that restriction in the next few years... I dunno.
But it might come back in the future:
Guy Steele wrote: One of the early design principles of Java was that heap allocation occurrs if and only if a construct involving the "new" keyword is executed. Adding full-blown closures violated this design principle. (Dynamic class loading also violated the principle, but users seemed to be comfortable with that, perhaps because they believed that "once the computation got going" no more heap allocation would occur.) Other features for Java release 1.5 will perform certain kinds of autoboxing, which also violates the design principle. This fact will make it easier to argue for restoring full-blown support for closures in the future.
It would be really nice to know more about what goes on inside Sun with respect to the Java language. I suppose we might just end up with endless blog-debate about what did/didn’t end up in the language, and about why such decisions were made.
Guy Steele wrote: Please remember that the design of a programming language consists not just in a laundry list of features, but also in making judicious choices of what to *omit* and, more importantly, in establishing design principles that are easy to understand.
The .net guys are blogging about it as it happens… See Chris Brumms blog.
Sorry but what you are telling is simply not true:
Such variables have to be final because the inner class must have a copy of the variable — the object could easily outlive the function and thus the scope of its variables — and it would be a semantic nightmare to allow changes to the multiply-extant variable.
Eric,
Such variables can be captured, so long as they are allocated "on the heap" in some sort of "holder" class (like a kind of mutable Integer).
You can easily fake it ofcourse by moving copies to an array or class that holds them for bothe the outer scope and the closure