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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a
Setto keep insertion order or allow duplicates, when duplicates are dropped and order is not guaranteed. - Using
ids + 4and expectingidsto change, when it returns a newSetsince the default one is immutable. - Indexing a set like
ids(0), which does not mean the first element but tests whether0is in the set.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: