August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to add, update, or delete elements when working with an immutable map.
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] ...Read now
Unlock full access