Set Class (Scala 3 Video)
A Scala Set
is an Iterable
type that has no duplicate elements.
Notes:
- There are mutable and immutable versions
- Don’t rely on the elements being in order
CRUD examples
// CREATE (available without an import)
val set = Set(1, 2, 3, 3, 3) // Set(1, 2, 3)
// empty set
val names: Set[String] = Set.empty
val b = names + "Alvin"
val c = b ++ List("Joe", "Fred")
// READ/access
val x = for e <- set yield e * 2
set(-1) // false
set(1) // true
set.contains(99) // false
// CREATE from a Range
val set = (1 to 10).toSet // Set[Int] = HashSet(5, 10, 1, 6, 9, 2, 7, 3, 8, 4)
// UPDATE
val a = Set(1, 2, 3)
val b = a + 4
val c = b ++ List(5, 6)
val d = c ++ List(1, 2, 3)
// DELETE (-, --)
val a = Set(1, 2, 3, 4, 5, 6)
val b = a - 1
val c = b - (2, 3)
val d = c -- List(4, 5)
// DELETE (filtering methods)
val a = (1 to 10).toSet
val b = a.filter(_ > 3)
val c = b.take(2)
Update: All of my new videos are now on
LearnScala.dev