#2380 List.each() and Read-Only Safe

SlimerDude Thu 27 Nov 2014

The docs of List.each() say This method is readonly safe. which I took to mean that it is not affected by subsequent changes to the list. But...

Void main() {
  list := [1, 2, 3, 4]
  list.each {
    list.remove(it)
  }
  echo(list)  // --> [2, 4]
}

Clearly the remove() statement affects the each() loop, which is not what I was expecting.

I can remedy the above by calling list.dup():

Void main() {
  list := [1, 2, 3, 4]
  list.dup.each {
    list.remove(it)
  }
  echo(list)  // --> [,]
}

But that is kindof what I thought each() did anyway.

Can someone confirm that I was wrong to expect the first bit of code to work? Cheers.

brian Thu 27 Nov 2014

Readonly safe just means that it won't raise an exception if you try it with a readonly or immutable list. So if you want to mutate the list during iteration, you definitely want to duplicate it first.

Login or Signup to reply.