Skip to content
Maps and Sets
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Map[K, V] for key-value, Set[T] for unique elements. Both are immutable by default — operations return new collections.

val ages = Map("Alice" -> 30, "Bob" -> 25)
ages("Alice")                    // 30 (throws if missing)
ages.get("Carol")                // None: Option[Int]
ages.getOrElse("Carol", 0)       // 0

val updated = ages + ("Carol" -> 40)   // new Map
val removed = ages - "Bob"

for ((name, age) <- ages) println(s"$name: $age")

val primes = Set(2, 3, 5, 7, 11)
primes.contains(7)               // true
primes + 13                      // Set(2, 3, 5, 7, 11, 13)
primes & Set(3, 5)               // intersection: Set(3, 5)

-> is just sugar for tuple creation: "Alice" -> 30 is ("Alice", 30).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…