Library contents

Scala Immutable Map versions

Keep yesterday’s price list available when the working menu changes.

A simple example

Immutable Map versions

  1. Start with A = 1
  2. Do this Copy the map, then set original A to 2
  3. Result Copy still has A = 1
The change in the original does not replace the entry in the copy.

Syntax

Scala syntax
val printed = prices
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Keep the price shown on yesterday's menu

A café changes its soup price after printing yesterday's menu. Accounts needs a snapshot of the earlier price to check old receipts even as the working price list changes.

Result4
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        var prices = Map("Soup" -> 4)
        val printed = prices
        prices = prices.updated("Soup", 5)
        println(printed("Soup"))
    }
}
Output
4

The printed menu keeps the earlier soup price of four.

Advertisements

Save a café price list

A counter freezes the morning menu before an afternoon update. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?

GivenMorning soup 4 · later 6
Worked result4

Print a desk assignment

A secretary prints room assignments before moving the club. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?

GivenPrinted East · later Hall
Worked resultEast

What to watch for

The map structure is immutable, but keys or values that are mutable objects need their own copying policy.

Documentation for Immutable Map versions