Library contents

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

  1. Start with Original A = 1
  2. Do this Create a version with A = 2
  3. Result Old 1, new 2
The updated map has the replacement value. The original still holds 1.

Syntax

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

First output line2
Lesson.scala
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"))
  }
}
Output
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

Advertisements

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?

Givengreen → 6, then green → 9
Worked result9

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?

Givensoup → 5, then soup → 6
Worked result6