Lambdas in for-each loops

Aleksey Shipilev aleksey.shipilev at oracle.com
Fri Aug 31 09:15:25 PDT 2012


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