Skip to content
Lesson 6 of 11

Step 1 of 5 · Reading · ~1 min

Learn

Collections

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).

Counting occurrences

groupBy buckets the elements by a key you choose; mapping over the result turns each bucket into its size, which is exactly a frequency table:

val words = List("the", "cat", "the")
val counts = words.groupBy(w => w).map(kv => (kv._1, kv._2.size))
counts("the")                    // 2
counts.keys.toList.sorted        // List(cat, the)

A Map has no defined iteration order, so sort the keys before you print anything that has to come out alphabetically.

Interpolation needs braces around expressions

In an s"..." string, a bare $ splices a plain identifier and nothing more. Anything with a dot, a call or an index needs ${...} around it:

val word = "the"
println(s"$word: ${counts(word)}")   // the: 2
println(s"$word: {counts(word)}")    // the: {counts(word)}

The second line is not an error, which is what makes it dangerous: the braces and the code inside them are printed literally, and the program runs happily to completion.

Up nextmatch ExpressionsPattern Matching

Discussion

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

Sign in to post a comment or reply.

Loading…