Immutable Data Patterns
Updating a Map
Add an entry without changing the original map.
Updating a Map
MapUpdate.scala
object Main {
def main(args: Array[String]): Unit = {
val price =
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 =
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 =
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)
}
}
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.