Accessing non-final local variables from a lambda expression

Rémi Forax forax at univ-mlv.fr
Fri Feb 26 06:06:09 PST 2010


Le 26/02/2010 14:56, Fatih Coskun a écrit :
>    
>>
>>      
>>> In BGGA, CfJ, and other languages with lambdas, one could write it
>>> simply like this
>>>
>>> <T>  Iterable<T>  everyOther(Iterable<T>  input) {
>>> ? ?boolean flag = true;
>>> ? ?return filter(input, (T t)->(flag ^= true));
>>> }
>>>
>>> But project lambda forbids access to mutable local variables from the
>>> enclosing scope.
>>>
>>>        
>> <T>  Iterable<T>  everyOther(Iterable<T>  input) {
>>     final boolean[] flag = new boolean[] { true };
>>     return filter(input, (T t)->(flag[0] ^= true));
>> }
>>
>> It's not beautiful, but not the end of the world either. And the
>> performance is comparable, since in any case you have to create and
>> dereference some heap object.
>>
>>
>>
>>      
>
> How about adding at least some syntactic sugar for that
> "array-wrapper-idiom"? The code looks really ugly, syntactic sugar would
> make it look better.
>
> Fatih

You're right it's ugly but at least there is no black magic somewhere.
The problem with a a syntactic sugar for shared state is that there is 
more than one way to 'unsugar' it
and those ways define very different semantics.

Should we let users use a gun that sometimes explode ?

Rémi





More information about the lambda-dev mailing list