11.15. Adding, Updating, and Removing Elements with Immutable Maps
Problem
You want to add, update, or delete elements when working with an immutable map.
Solution
Use the correct operator for each purpose, remembering to assign the results to a new map.
To be clear about the approach, the following examples use an
immutable map with a series of val
variables. First, create an immutable map as a val
:
scala> val a = Map("AL" -> "Alabama")
a: scala.collection.immutable.Map[String,String] =
Map(AL -> Alabama)
Add one or more elements with the +
method, assigning the result to a new
Map
variable during the
process:
// add one element scala>val b = a + ("AK" -> "Alaska")
b: scala.collection.immutable.Map[String,String] = Map(AL -> Alabama, AK -> Alaska) // add multiple elements scala>val c = b + ("AR" -> "Arkansas", "AZ" -> "Arizona")
c: scala.collection.immutable.Map[String,String] = Map(AL -> Alabama, AK -> Alaska, AR -> Arkansas, AZ -> Arizona)
To update a key/value pair with an immutable map, reassign the key
and value while using the +
method,
and the new values replace the old:
scala> val d = c + ("AR" -> "banana")
d: scala.collection.immutable.Map[String,String] =
Map(AL -> Alabama, AK -> Alaska, AR -> banana, AZ -> Arizona)
To remove one element, use the -
method:
scala> val e = d - "AR"
e: scala.collection.immutable.Map[String,String] =
Map(AL -> Alabama, AK -> Alaska, AZ -> Arizona)
To remove multiple elements, use the -
or --
methods:
scala> val f = e - "AZ" - "AL"
f: scala.collection.immutable.Map[String,String] ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.