Lambdas in for-each loops

Remi Forax forax at
Wed Sep 5 02:01:54 PDT 2012

On 09/05/2012 10:51 AM, Maurizio Cimadamore wrote:
>> 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.

Lambdas require target typing, so we should update the spec/compiler to 
have target typing everywhere it's needed. So foreach loop should allow 
target typing (once array are ruled out) and conditional expression 
should allow target typing too.

> Maurizio


More information about the lambda-dev mailing list