lambda expression parameters

Dan Smith daniel.smith at oracle.com
Tue Dec 18 18:23:48 PST 2012


On Dec 18, 2012, at 5:57 PM, Julian Hyde <julianhyde at gmail.com> wrote:

> My opinion is that lambda parameters should be final by decree. For example, in
> 
> for (int i = 0; i < 10; i++) {
>  foo(i -> ++i);
> }
> 
> the parameter 'i' to the lambda doesn't have a traditional declaration (such as 'int i' or 'final int i') and so a naive reader would be surprised to learn that it is actually different from the variable 'i' in the enclosing loop.

We've got this covered: lambda parameters are not allowed to shadowing local variables in the enclosing context.

I thought about a similar example, without shadowing:

list.map(x -> ++x)
or
list.map(x -> x = x+1)

The user might not realize the the mutation is meaningless, but it's harmless: the effect of the 'map', in any case, is to increment all elements by one.

More problematic if the naive user tries post-increment:

list.map(x -> x++)

Now the 'map' is a no-op.  Not good, although this indicates a basic misunderstanding about what lambdas mean, and one that beginners will probably figure out pretty quickly.  But maybe this is the best argument for _some_ sort of special error detection.

—Dan


More information about the lambda-dev mailing list