Lambdas in for-each loops
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Wed Sep 5 07:19:19 PDT 2012
On 05/09/12 15:02, Remi Forax wrote:
> 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
>
>
I think that's a weak argument - what about:
List<String> ls = new ArrayList<>();
ls.add("Hello");
ls.add("World!");
for (String s : ls) {
if (true) { ls.remove("World!"); }
}
Simple or not simple?
Maurizio
More information about the lambda-dev
mailing list