11.24. Adding Elements to a Set


You want to add elements to a mutable set, or create a new set by adding elements to an immutable set.


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 += 1
res0: 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 += 2
res2: 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:


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 ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.