Lambdas in for-each loops
Remi Forax
forax at univ-mlv.fr
Wed Sep 5 07:02:34 PDT 2012
On 09/05/2012 03:55 PM, Sergey Kuksenko wrote:
> On 09/05/2012 05:51 PM, Remi Forax wrote:
>> On 09/05/2012 03:26 PM, Brian Goetz wrote:
>>>> At such case I have a serious question - why for-each loop doesn't
>>>> allow
>>>> to use Iterator? Why do we need only Iterable (and arrays of course) ?
>>>> May be it may sense to expand for-each loop itself and detach the
>>>> problem from lambda? it looks like we something like project
>>>> Coin2.0 for
>>>> such things.
>>>
>>> This was a hot issue during the development of the foreach loop. In
>>> the end, the EG decided that allowing Iterator in foreach loop was
>>> potentually confusing, since as a side effect of being iterated, the
>>> iterator was "drained".
>>>
>>>
>> Also, you can write horrible things like,
>> Iterator<String> it = collection...
>> for(String s: it) { // ok, simple loop
>> if (...) {
>> ...
>> it.remove(); // not a simple loop anymore
>> }
>> }
>>
>> if you read the code, a foreach loop should always be a simple loop
>> with no side effect on the iterable.
>>
>> Rémi
>>
> Ok. Let's do:
>
> Iterator<String> it = collection...
> for(String s: asIterable(it) /*or lambda*/) { // ok, simple loop
> if (...) {
> ...
> it.remove(); // not a simple loop anymore
> }
> }
>
> I see the same.
>
No, because the header of your loop is not simple anymore.
BTW, that's why I prefer the lambda syntax, because you add syntax 'noise',
the lambda or the method reference, to the foreach loop,
so the fact that's it's a not a plain old loop is clearly visible.
for(String s: getACollection()) { // simple loop
}
for(String s: () -> getAnIterator()) { // not a simple loop
}
As a writer, you pay a syntactic price (burger arrow?) in order to warn
the reader.
Rémi
More information about the lambda-dev
mailing list