3 ms·
> 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 pr
by chimeracoder 13y ago
> 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.
"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).
- RyanZAG 13y agoYes, final is only 'shallow immutability' and only ensures that the reference itself is immutable. This is the only part that applies to closures though: the reference that is accessible from the closure. 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.