Lambdas in for-each loops

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Wed Sep 5 02:52:22 PDT 2012


On 05/09/12 10:01, Remi Forax wrote:
> 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.
Target type in conditional is already supported.

What I'm saying is that the rule-out-the-array approach is obvious 
enough when the expression of an enhanced for loop IS a lambda or a 
method reference. If it's a conditional should we pass in Iterable<X> 
regardless of the conditional subexpressions? What if it's something like:

for (String s : ? new String[] { "" } : new String[] { "" })

If you pass in the target type in this case you will get a compile-time 
error as String[] is not compatible with Iterable<String>.

Also, the deliberate simplification of considering the target type to be 
Iterable<X> where X is the variable type, would lead to other problems:

Iterable<? extends String> ies = ...;

for (String s : ? ()-> { ... } : ies)

This would be a compile-time error, as Iterable<#1>, where #1 <: String 
is not compatible with Iterable<String> (the 'supposed' target type). 
However, the following:

for (String s : ies)

compiles now.

The nature of the for-each loop is very peculiar - an attempt to evolve 
it and treat it as any other target-typing context is error-prone at 
best because, as I said, the language works backwards in this particular 
case.

Maurizio



More information about the lambda-dev mailing list