On 27 March 2015 at 02:18, Tankerbay <
tank...@gmail.com> wrote:
> Wow, I had no idea this would work:
> def list = [2,4,6,7,5,9,10,11,12,14,15]
> list.each { if ( it % 2 == 0 ) { list -= it } }
> assert list == [7,5,9,11,15]
Looks can be deceiving - notice that the final list is not the list
you started with:
def list = [1, 2, 3, 4, 5]
def list2 = list
assert
list2.is(list)
list.each { if (it % 2) list -= it }
assert !
list2.is(list)
>
> And I'm kind of shocked it does... I'm guessing that the each iterator has
> an immutable form of the original list in it as it traverses.
The minus operator actually returns a *new* list with elements from
the original list minus the occurrences of the operand on the right.
>
> That said, I wouldn't do this, it violates functional programming's
> immutability principle in a big way. I'd use:
> def newlist = list.findAll { it % 2 != 0 }
Yes, that's the right way to do it.
>
> But if you really wanted to modify the original list, I guess you can.
`each` method does use Iterator, which allows elements to be removed
from the collection, but that iterator is inaccessible from the `each`
Closure block. If one wanted to mutate the original collection by
removing elements from it, then using `each` would not be the proper
way.
Cheers,
Dinko
>
>
>
>
> On Thu, Mar 26, 2015 at 4:53 PM, Matthias F. Brandstetter <
hai...@gmail.com>
> wrote:
>>
>> Let's say I have a collection 'list' with some relements in it. Now I am
>> iterating over all elements, to remove some of them:
>>
>> list.each {
>> println it
>> if(it > 0) {
>> list -= it
>> }
>> }
>>
>> From my experience it seems to be safe to do so, i.e. to remove an element
>> directly from within the "each" closure. That is, I don't get any access
>> modification exception.
>>
>> I know from Java however that you usually don't want to do such a thing in
>> a loop. Instead one should use an Iterator instead. Now, since there seems
>> to be no issue in Groovy, is it safe to go that direct way here?
>>
>> Kind regards, Matthias
>>
>>
>> --
>> Matthias F. Brandstetter
>>
hai...@gmail.com
>> @maflobra
>
>
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email