Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created October 18, 2012 03:25
Show Gist options
  • Select an option

  • Save mpilquist/3909703 to your computer and use it in GitHub Desktop.

Select an option

Save mpilquist/3909703 to your computer and use it in GitHub Desktop.
Don't mutate stuff while iterating
scala> val s = MSet() ++ (1 to 20)
s: scala.collection.mutable.Set[Int] = Set(5, 9, 15, 16, 18, 14, 19, 2, 20, 6, 1, 13, 4, 12, 7, 3, 8, 17, 11, 10)
scala> s.size
res16: Int = 20
scala> s foreach { n => if (n % 2 == 0) s -= n }
scala> s.size
res18: Int = 11
scala> s
res19: scala.collection.mutable.Set[Int] = Set(15, 9, 18, 19, 1, 13, 17, 7, 3, 11, 5)
scala> s foreach { n => if (n % 2 == 0) s -= n }
scala> s.size
res21: Int = 10
@mpilquist

Copy link
Copy Markdown
Author

Ignore the fact that this can be done with calling filter on the set. The point here is that ConcurrentModificationException does not occur and instead, the foreach silently skips elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment