By Alvin Alexander. Last updated: June 4, 2016
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:
- http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.Set
- http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.SortedSet
- http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.LinkedHashSet