Approximating closures in Java
by Kevin Dangoor
Charles Miller wrote a nice article: The Fishbowl: Closures and Java: a Tutorial. He talks about using inner classes to somewhat approximate closures. He also says that “To implement them properly would involve making changes to some pretty fundamental parts of the JVM”, which I’m not sure is completely true. It may be possible for Sun to create java.lang.Function and then add some syntactic sugar to the compiler to create
1) Functions that can be passed around easily, which is something that is potentially quite useful
2) Real closures (but there may be more issues to the scoping that I’m just not thinking through)
I am not really qualified to make this call, but I’m pretty sure that to implement closures properly, you’d need to make stack frames into first-class objects, which the JVM can’t do.
You could simulate a lot of cases by having the compiler generate in- and out- parameters for the generated anonymous inner class, but that’s yet another ugly hack, and would probably fail unexpectedly if you tried to do anything outside the simple case.
That’s the great thing about blogging… you’re allowed to say anything, even things you’re unqualified to say
You’re right that somewhere along the way you do need to keep track of the stack frame associated with the closure. The trick is to think of the compiler/language as a separate piece from the JVM – which is a big advantage that Microsoft.NET has. The fact that Python, Javascript and Ruby all run on the JVM show that the capabilities of the VM are not necessarily tied to the syntax of the language.
Though I don’t know for certain, I’m under the impression that the Java 1.5 language changes do not involve changes to the JVM. Things like generics seem like a big thing, but it’s all syntax that is managed by the compiler. I bet there are many more bits of goodness that Sun could do without changing the JVM.