Rajashree Gr Rajashree Gr -4 years ago 212
Scala Question

Scala Map update

I want to update Map value which is present in another Map. When I try to update is says 'value update is not a member of Option[scala.collection.immutable.Map[Int,Int]]'.

I tried to convert the value to Map but still, it didn't work for me.

val map = Map("one" -> Map(1 -> 11), "two" -> Map(2 -> 22))
val value = map1.get("one")
value(1) = 100 //value update is not a member of Option[scala.collection.Map[Int,Int]]

Answer Source

There are two mistakes you are making.

  1. Calling get on a Map will return an Option, hence you are not able to set the value.

  2. You are using immutable Map when your operation/purpose is to update the value of some key, for which you need to use mutable map.

Let us try to do the write some snippets to solve these two problems.

scala> val map = Map("one" -> Map(1 -> 11), "two" -> Map(2 -> 22))
map: scala.collection.immutable.Map[String,scala.collection.immutable.Map[Int,Int]] = Map(one -> Map(1 -> 11), two -> Map(2 -> 22))

scala> val valueOption = map.get("one")
valueOption: Option[scala.collection.immutable.Map[Int,Int]] = Some(Map(1 -> 11))

scala> val value = map("one")
value: scala.collection.immutable.Map[Int,Int] = Map(1 -> 11)

scala> value(1) = 100
<console>:13: error: value update is not a member of scala.collection.immutable.Map[Int,Int]
       value(1) = 100

You should notice the difference between getting the value using .get and directly using parenthesis. This is a more understandable error and no need to understand Scala magic happening underneath.

Now if you repeat the same statements after importing mutable Map, you will be able to get what you are trying to achieve.

scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map

scala> val map = Map("one" -> Map(1 -> 11), "two" -> Map(2 -> 22))
map: scala.collection.mutable.Map[String,scala.collection.mutable.Map[Int,Int]] = Map(one -> Map(1 -> 11), two -> Map(2 -> 22))

scala> val value = map("one")
value: scala.collection.mutable.Map[Int,Int] = Map(1 -> 11)

scala> value(1) = 100

scala> map
res2: scala.collection.mutable.Map[String,scala.collection.mutable.Map[Int,Int]] = Map(one -> Map(1 -> 100), two -> Map(2 -> 22))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download