modify scala map values

10,037

I'm not sure what createMap() function returns, but my guess is that it returns a Map[String, Int].

If this is true, then your code fails because Map[String, Int] is immutable, and you can't reassign value to immutable map with this code newMap(k) = 2 * v. You must use mutable.Map[String, Int] here.

Example code (in scala REPL):

scala> val x = Map("foo" -> 1, "bar" -> 2)
x: scala.collection.immutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> var y: scala.collection.mutable.Map[String, Int] = scala.collection.mutable.Map(x.toSeq: _*)
y: scala.collection.mutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> y("foo") = 3

scala> y
res2: scala.collection.mutable.Map[String,Int] = Map(foo -> 3, bar -> 2)

However, what you need here is just a new map with all the values being doubled, you can simply do:

x.map { case (k, v) => k -> 2 * v }
Share:
10,037
xichen
Author by

xichen

Updated on June 18, 2022

Comments

  • xichen
    xichen almost 2 years

    I has learn scala recently,but I found a question when modify map values.

        def exercise1():Map[String, Int]={
          val map = createMap()
          var newMap = map
         for((k,v) <-  map){
           newMap(k) = 2 * v;
         }
          newMap
        }
    

    the function exercise1 can running. But when I change a line like next

    newMap(k) = v * 2;
    

    I found it failed, why?