Start learning free

LESSON 234 OF 677 · SETS

Sets in Scala

Lesson

TL ; DR:

A mutable Set holds values without repeats. Adding a value that is already in it changes nothing.


val pets = scala.collection.mutable.Set[String]()    // an empty set
pets += "cat"
pets += "dog"
pets += "cat"                     // already in it, no change

println(pets.size)                // 2
println(pets.contains("dog"))     // true


Full lesson:

An ArrayBuffer keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • scala.collection.mutable.Set[String]() makes an empty set of strings.
  • s += x puts x in the set s.
  • s.contains(x) is true when x is in the set.
  • s.size gives how many values the set holds.
  • scala.collection.mutable.Set[String](buf.toSeq: _*) builds a set from the ArrayBuffer buf. Its repeats go in once.

The : _* hands the values to the set one by one. It takes an Array or a plain sequence. .toSeq turns the ArrayBuffer into one.

Checking s.contains(x) is fast, even for a big set. A list's contains looks at the values one by one.

Scala's plain Set can't change. += on a val of it doesn't compile. That's why we use scala.collection.mutable.Set.

A set has no order. A printed set may show its values in any order.


Your task

The camp's sign-up list, names, has some names twice. Build a mutable set named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check