11.24. Adding Elements to a Set
Problem
You want to add elements to a mutable set, or create a new set by adding elements to an immutable set.
Solution
Mutable and immutable sets are handled differently, as demonstrated in the following examples.
Mutable set
Add elements to a mutable Set with the +=, ++=,
and add methods:
// use var with mutable scala>var set = scala.collection.mutable.Set[Int]()set: scala.collection.mutable.Set[Int] = Set() // add one element scala>set += 1res0: scala.collection.mutable.Set[Int] = Set(1) // add multiple elements scala>set += (2, 3)res1: scala.collection.mutable.Set[Int] = Set(2, 1, 3) // notice that there is no error when you add a duplicate element scala>set += 2res2: scala.collection.mutable.Set[Int] = Set(2, 6, 1, 4, 3, 5) // add elements from any sequence (any TraversableOnce) scala>set ++= Vector(4, 5)res3: scala.collection.mutable.Set[Int] = Set(2, 1, 4, 3, 5) scala>set.add(6)res4: Boolean = true scala>set.add(5)res5: Boolean = false
The last two examples demonstrate a unique characteristic of the
add method on a set: It returns
true or false depending on whether or not the
element was added. The other methods silently fail if you attempt to
add an element that’s already in the set.
You can test to see whether a set contains an element before adding it:
set.contains(5)
But as a practical matter, I use += and ++=, and ignore whether the element was
already in the set.
Whereas the first example demonstrated how to create an empty set, you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access