Lambdas in for-each loops

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Aug 31 09:22:08 PDT 2012


Quoting from the spec EDR:

" The expression in an enhanced for loop is not in a poly context 
because, as the construct is currently defined, it is as if the 
expression were a receiver: exp.iterator() (or, in the array case, 
exp[i]). It is plausible that an Iterator could be wrapped as an 
Iterable in a for loop via a lambda expression (for (String s : () -> 
stringIterator)), but this doesn't mesh very well with the semantics of 
Iterable."

Maurizio

On 31/08/12 17:15, Aleksey Shipilev wrote:
> Hi,
>
> Maybe this had been already discussed in EG or this list, but I haven't
> found any relevant discussions.
>
> Here is the deal: it some contrived cases I would like to use the
> Iterator in for-each loop. I can do that by pretending being Iterable,
> and having in mind Iterable is the functional interface, I can do this:
>
>      public void test() {
>          Iterator<String> it =  Arrays.asList("1", "2", "3").iterator();
>          for (String s : () -> it) {
>              System.out.println(s);
>          }
>      }
>
> However, it does not compile:
>
> LambdaTest.java:9: error: lambda expression not expected here
>          for (String s : () -> it) {
>                          ^
> 1 error
>
> It helps to both cast to explicit Iterable:
>
>      public void test() {
>          Iterator<String> it =  Arrays.asList("1", "2", "3").iterator();
>          for (String s : (Iterable<String>)()->it) {
>              System.out.println(s);
>          }
>      }
>
> ...or store in local:
>
>      public void test() {
>          Iterator<String> it =  Arrays.asList("1", "2", "3").iterator();
>          Iterable<String> itr = ()->it;
>          for (String s : itr) {
>              System.out.println(s);
>          }
>      }
>
> ...but it does not look as nice. Is the current javac behavior the part
> of "not implemented yet" series; or is it a bug; or is it a feature, and
> we are sticking with it?
>
> Thanks
> -Aleksey.
>
>



More information about the lambda-dev mailing list