Reputation: 111
I'm using scala 2.9.1, when I try this code:
import scala.collection.mutable
val a = mutable.Set(1,2,3,4,7,0,98,9,8)
a.foreach(x => { println(x); a.remove(x) })
the result was something like
0
98
2
1
4
3
8
which did not list all the elements of a. After this, a becomes Set(9, 7) instead of empty set. It looks very weird to me, is it a bug or we just cannot modify the set itself when doing foreach?
Upvotes: 9
Views: 2278
Reputation: 370455
You may not modify a collection while traversing or iterating over it.
This is the same in Scala as it is in Java (and most other programming languages/libraries). Except that in Java, the Iterator
class provides a remove
method that can be used instead of the collection's remove
method to remove elements while iterating using that Iterator
(but will invalidate any other iterators of that collection that might be in use). Scala Iterators provide no such method.
Upvotes: 10