Lambdas in for-each loops

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Wed Sep 5 01:51:14 PDT 2012


>
> I've been saying that lambda expressions can be used in any context 
> that expects an instance of a FI type. It would be nice to have no 
> exceptions to that, if possible (are there others besides this foreach 
> loop situation?).
The for-each context is not straightforward - when the compiler sees:

for (String s : exp)

it doesn't exactly expects an Iterable<String>, as exp can be either an 
array or an Iterable. Howvere, even if we ruled out the array case, we 
still would have the problem that the variable declaration 's' 
corresponds to several potential target types (not just one) as there 
might be wildcards involved. In other words, this is not a context in 
which a target type is expected - things like method inference also 
doesn't work here:

<E> Iterable<E> it() { ... }

for (String s : it()) //error

Type-checking for for-each loop works the other way around - first the 
type of the expression is determined in isolation - if that type is some 
Iterable<X> the compiler checks that X is compatible with the type of 
the for each variable decl.

Of course the compiler could special case situations in which the 
expression is a lambda/method reference and pass in a target type that 
is Iterable<X> where X is the type of the variable, but that would feel 
a bit brittle and would not scale to situations in which the lambda is 
nested in i.e. a conditional expression.

Maurizio




More information about the lambda-dev mailing list