Effectively final effective?

Artur Biesiadowski abies at adres.pl
Wed Feb 24 15:37:40 PST 2010


Mark Thornton wrote:
>
> Yet would not many developers be surprised to discover that they 
> couldn't change an apparently ordinary local variable because it had 
> been captured by a lambda (or anonymous inner class) some lines previously.
>
>   

What about yet another solution ?

------------------
int x = 1;

Runnable x = new Runnable() {public void run() {
   use(x); // you can use x as capture at moment of creation here
   //x++; // illegal, x is not allowed be modified from anonymous/lamba 
scopes
}};

x = 2; // you CAN mutate it further in outside scope

x.run(); // use(1) will be called inside, mutation of x is not visible 
in already captured environment
-----------------


I think this has all the benefits:
- no need to write final anymore to just capture the local variable
- existing source code still works without any changes
- works with index variables of 'for' as expected, even if 
lambdas/classes created inside are executed later
- you can get very clear warning when trying to mutate x inside 
lambda/anonymous class ("Cannot modify local variable x of enclosing 
scope from within lambda/anonymous class")

Only tricky part is that somebody might try to communicate with 
lambda/anonymous class through local variable, hoping that assignment 
x=2 above will become visible at some point inside already captured 
closure. Still, I think that this is use case complicated enough that 
people who will try it can be explained why it is not working.

Regards,
Artur Biesiadowski


More information about the lambda-dev mailing list