← Back to Scala Course | Chapter 6: Collections Basics | Lesson 5 of 8

Set

A Set is a bag that never holds duplicates, like a sticker collection where you keep only one of each. Adding something already there changes nothing.

In this page:

  1. Set
Syntax
scala
val set = Set(value1, value2, value3)
val bigger = set + value
set.contains(value)

Set

A Set stores unique elements with no defined order and no duplicates -- adding an element that already exists has no effect.

Set(1, 2, 3) creates an immutable set by default; scala.collection.mutable.Set provides a mutable version supporting +=/-=. Sets are ideal for membership tests and removing duplicates from data.

Note: Adding a duplicate value to a Set is silently a no-op -- the set's size never changes for an already-present element.

Example: Set

markup
object Main extends App {
  val ids = Set(1, 2, 3)
  val expanded = ids + 2 + 4 // 2 already exists, ignored

  println(expanded)
  println(expanded.contains(3))
  println(expanded.size)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a Set to keep insertion order or allow duplicates, when duplicates are dropped and order is not guaranteed.
  2. Using ids + 4 and expecting ids to change, when it returns a new Set since the default one is immutable.
  3. Indexing a set like ids(0), which does not mean the first element but tests whether 0 is in the set.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.