Scala Map.updated and getOrElse
updated returns an immutable map with one key added or replaced. getOrElse supplies an initial count for previously unseen keys.
A simple example
Map.updated and getOrElse
- Start with Original A = 1
- Do this Create a version with A = 2
- Result Old 1, new 2
Syntax
val next = counts.updated(key, counts.getOrElse(key, 0) + 1)
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Build counts while preserving the original snapshot
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
object Lesson {
def main(args: Array[String]): Unit = {
val baseline = Map("west" -> 1)
val result = List("east", "east").foldLeft(baseline) { (counts, key) =>
counts.updated(key, counts.getOrElse(key, 0) + 1)
}
println(result("east"))
println(baseline.contains("east"))
}
}
2 false
Keeping the original map allows two snapshots to coexist. A fold can build a frequency table without mutating the baseline that the caller passed in.
Scala documentation for Map.updated and getOrElse
Revise a locker assignment
A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
Correct a menu price
A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?