Accessing non-final local variables from a lambda expression

Lawrence Kesteloot lk at teamten.com
Fri Feb 26 00:23:42 PST 2010


> 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.

Lawrence


More information about the lambda-dev mailing list