capturing (or not) mutable local variables

Osvaldo Pinali Doederlein opinali at gmail.com
Mon Nov 22 05:35:41 PST 2010


On 22/11/2010 07:21, Alessio Stalla wrote:
> I'd like to point out that, in my experience with Lisp, the mutability
> of the closed-over variables is rarely if ever used to update a local
> to be used further down the same function/method; in other words,

No much Lisp here, but in other langs like Smalltalk, full closures are 
essential for user/library-defined control structures. That is the big 
door that's being closed by the current closures spec; but we're already 
past this discussion, we're not going to have any special syntax for 
control abstractions. Still, I see this limitation as extra, artificial, 
unnecessary complexity. On the concurrency argument, I'm with Pavel and 
others - like it or not the Java language is deeply rooted in the 
"serial past", mutability is its main paradigm, and it's probably 
impossible to really fix that (even to reach a decent hybrid-paradigm 
language) while maintaining backwards compatibility.  The current 
closures spec will make things worse for serial code, while not 
necessarily making anything better for concurrent code. That could be 
different if Java8 had a broader revision towards functional behavior - 
for example, extra syntax like const qualifiers, inference to detect 
immutability and function pureness etc. (The late JavaFX Script was 
already making some nice progress in these directions, hopefully this 
will continue in Visage and other Java-like JVM langs). But such 
revision is not in the plans for Java8 (although the Checker Framework is).

A+
Osvaldo

> int i = 0;
> foo.foreach(#{ x ->  i += x; });
> use(i);
>
> is not a common code pattern, and it's generally considered bad style.
> Instead, mutable captured variables are used much more often as a way
> to give some private state to a closure, effectively turning it into a
> lightweight object (in the OO sense). So, while I do believe that
> "true" closures should close over their lexical environment without
> restrictions, including mutability, I think in Java the issue
> isn't/won't be that important; if you want private state you can still
> use a plain old inner class and explicitly capture (copy) the locals
> you're interested in -  after all, closures are going to be "syntax
> sugar" for SAM types anyway - or you can use final/effectively final
> (+ maybe AtomicXxx if you need it).
>



More information about the lambda-dev mailing list