Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A bug of mutable.Set.foreach in scala?

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?

like image 877
user1923692 Avatar asked Dec 22 '12 15:12

user1923692


1 Answers

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.

like image 98
sepp2k Avatar answered Nov 02 '22 10:11

sepp2k