Add an entry without changing the original map.

map-update Adding a key with `+` returns a new map. The original map keeps its size, and a lookup on the new map reads the added value.

Updating a Map

price
MapUpdate.scala
Replay: real traced execution (multi-file project)
object Main {
  def main(args: Array[String]): Unit = {
    val price = 30
    val base = Map("a" -> 10, "b" -> 20)
    val updated = base + ("c" -> price)
    val found = updated.getOrElse("c", 0)

    println("baseSize=" + base.size)
    println("updatedSize=" + updated.size)
    println("c=" + found)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val price = 15
    val base = Map("a" -> 10, "b" -> 20)
    val updated = base + ("c" -> price)
    val found = updated.getOrElse("c", 0)

    println("baseSize=" + base.size)
    println("updatedSize=" + updated.size)
    println("c=" + found)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val price = 50
    val base = Map("a" -> 10, "b" -> 20)
    val updated = base + ("c" -> price)
    val found = updated.getOrElse("c", 0)

    println("baseSize=" + base.size)
    println("updatedSize=" + updated.size)
    println("c=" + found)
  }
}
  1. price ← 30, base ← Map(a -> 10, b -> 20), updated ← Map(a -> 10, b -> 20, c -> 30)

    1object Main {2  def main(args: Array[String]): Unit = {3    val price→ 30 = 30 //@price=15, 504    val base→ Map(a -> 10, b -> 20) = Map("a" -> 10, "b" -> 20)5    val updated→ Map(a -> 10, b -> 20, c -> 30) = baseMap(a -> 10, b -> 20) + ("c" -> price30)6    val found→ 30 = updatedMap(a -> 10, b -> 20, c -> 30).getOrElse("c", 0)78    println("baseSize=" + base.size2)9    println("updatedSize=" + updated.size3)10    println("c=" + found30)11  }12}
    outputbaseSize=2
    updatedSize=3
    c=30
  1. price ← 15, base ← Map(a -> 10, b -> 20), updated ← Map(a -> 10, b -> 20, c -> 15)

    1object Main {2  def main(args: Array[String]): Unit = {3    val price→ 15 = 154    val base→ Map(a -> 10, b -> 20) = Map("a" -> 10, "b" -> 20)5    val updated→ Map(a -> 10, b -> 20, c -> 15) = baseMap(a -> 10, b -> 20) + ("c" -> price15)6    val found→ 15 = updatedMap(a -> 10, b -> 20, c -> 15).getOrElse("c", 0)78    println("baseSize=" + base.size2)9    println("updatedSize=" + updated.size3)10    println("c=" + found15)11  }12}
    outputbaseSize=2
    updatedSize=3
    c=15
  1. price ← 50, base ← Map(a -> 10, b -> 20), updated ← Map(a -> 10, b -> 20, c -> 50)

    1object Main {2  def main(args: Array[String]): Unit = {3    val price→ 50 = 504    val base→ Map(a -> 10, b -> 20) = Map("a" -> 10, "b" -> 20)5    val updated→ Map(a -> 10, b -> 20, c -> 50) = baseMap(a -> 10, b -> 20) + ("c" -> price50)6    val found→ 50 = updatedMap(a -> 10, b -> 20, c -> 50).getOrElse("c", 0)78    println("baseSize=" + base.size2)9    println("updatedSize=" + updated.size3)10    println("c=" + found50)11  }12}
    outputbaseSize=2
    updatedSize=3
    c=50