Lambdas in for-each loops

Dan Smith daniel.smith at oracle.com
Wed Sep 5 15:15:40 PDT 2012


Aleksey: Maurizio gave you the party line answer, which is where we're at right now.  The EG still has this as an open question, though (i.e., we may decide to change how this works in the future).  Various arguments that have been made for/against are scattered throughout the rest of this thread. :-)

EG people: Yes, we discussed this a month ago, with various arguments supporting it being made, and yes this is something that will come up again.  No need to re-debate it all here. :-)  The main blocker right now is that we need the libraries to come into sharper focus so that we can address the related issue of how those features interact with for-each (if at all).

—Dan

On Aug 31, 2012, at 10:22 AM, Maurizio Cimadamore <maurizio.cimadamore at oracle.com> wrote:

> 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