Lambdas in for-each loops
Sergey Kuksenko
sergey.kuksenko at oracle.com
Wed Sep 5 06:55:52 PDT 2012
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.
--
Best regards,
Sergey Kuksenko
More information about the lambda-dev
mailing list