typestar

Maps in Scala

A seed drawer as a Map, read two different ways and updated without mutation.

// a Map literal pairs each key with a value using ->
val packets: Map[String, Int] =
  Map("basil" -> 40, "dill" -> 12, "kale" -> 75)

// apply reads a key directly, and throws when the key is absent
val basilSeeds: Int = packets("basil")

// get wraps the answer in an Option, so a miss is a value
val foundDill: Option[Int] = packets.get("dill")
val missingSage: Option[Int] = packets.get("sage")

// getOrElse reads the key or falls back, all in one step
val sageCount: Int = packets.getOrElse("sage", 0)

// updated returns a new Map with one key rewritten
val afterSowing: Map[String, Int] = packets.updated("kale", 60)

// + takes a fresh pair; the original map still holds three entries
val withSage: Map[String, Int] = packets + ("sage" -> 25)
val stillThree: Boolean = packets.size == 3

How it works

  1. Map("basil" -> 40, "dill" -> 12, "kale" -> 75) pairs each key with a value, and packets("basil") reads one key directly, throwing when the key is absent.
  2. packets.get("dill") returns an Option[Int], so the absent packets.get("sage") is an ordinary value rather than an error, and packets.getOrElse("sage", 0) reads and falls back in one step.
  3. packets.updated("kale", 60) rewrites one key and packets + ("sage" -> 25) adds a pair, both returning new maps while packets.size == 3 still holds.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
794
Tokens
125
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 107 seconds.

Type this snippet

Step 2 of 3 in Collections, step 11 of 27 in Language basics.

← Previous Next →

Maps in other languages