How to create a mutable Set in Scala

Scala Set FAQ: How do I create a mutable Set in Scala?

To create a mutable set in Scala, first determine the type of set you want. You do this because the mutable Set is actually a trait, and you need to determine which concrete implementation you want.

For instance, if you want a SortedSet of String, define it like this:

val names = scala.collection.mutable.SortedSet[String]()

Then you can add elements to the set later like this:

names += "Kim"
names += "Al"
names += "Terry"
names += "Julia"

Here's what this looks like in the Scala REPL:

scala> val names = scala.collection.mutable.SortedSet[String]()
names: scala.collection.mutable.SortedSet[String] = TreeSet()

scala> names += "Kim"
res0: names.type = TreeSet(Kim)

scala> names += "Al"
res1: names.type = TreeSet(Al, Kim)

scala> names += "Terry"
res2: names.type = TreeSet(Al, Kim, Terry)

scala> names += "Julia"
res3: names.type = TreeSet(Al, Julia, Kim, Terry)

Scala mutable set links

For more information, here are a few links to the Scala API docs related to mutable sets: