by RyanZAG · 13y ago · 0 comments
Java only allows 'final' or immutable variables to be passed into closures. This prevents the value from changing and ensures that the compiler catches the problem if you try to pass a changing value into a closure.
It was pretty new to me and kinda not sensed the concept behind closures.
I would like to know what you think about the explanation I provided in the post about closures. Did I get the point? Don't hesitate to tell me if I'm totally wrong
For your original code example, the Java compiler would have failed with an error that the variable 'i' was not declared final (immutable). Java 8 supports lambdas now, but in earlier Java versions you would have had to add a line like 'final int fi = i;' and you could then have used the fi inside the closure. The point in my previous post that the compiler detecting this ambiguity is exceptionally helpful and I'd prefer more languages to follow that route.
With Java 8 lambdas, it's much the same but with some nice syntax to make it easier[1].
[1] http://java.amitph.com/2012/08/at-first-sight-with-closures-...
"Final" in Java does not make objects immutable. The object itself can have mutator methods that change instance variables/attributes of the object, even though the identifier is declared as final.
IIRC, the only reason Java requires variables in closures to be final is for garbage collection. "final" allows the runtime to know that the identifier itself isn't going to be rebound to a different object, which is different from knowing that the object that it is being bound to won't change internally.
(Disclaimer: It's been a while since I used Java proper, so I'm probably missing some subtlety with the explanation of the rationale, but I'm pretty sure it's something along these lines).
Full immutability is left up to the programmer / api designer as with javascript - as it should be, imo. Trying to optimize fully immutable data-structures when performance becomes an issue in an inner loop down the line is a nightmare I would not recommend.