Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Map update

Tags:

scala

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]]
like image 479
Rajashree Gr Avatar asked Aug 10 '26 05:08

Rajashree Gr


1 Answers

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))
like image 84
saheb Avatar answered Aug 13 '26 01:08

saheb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!