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
Map("basil" -> 40, "dill" -> 12, "kale" -> 75)pairs each key with a value, andpackets("basil")reads one key directly, throwing when the key is absent.packets.get("dill")returns anOption[Int], so the absentpackets.get("sage")is an ordinary value rather than an error, andpackets.getOrElse("sage", 0)reads and falls back in one step.packets.updated("kale", 60)rewrites one key andpackets + ("sage" -> 25)adds a pair, both returning new maps whilepackets.size == 3still holds.
Keywords and builtins used here
BooleanIntMapOptionStringval
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.
Step 2 of 3 in Collections, step 11 of 27 in Language basics.