Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify scala map values

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?

like image 690
xichen Avatar asked Mar 08 '23 21:03

xichen


1 Answers

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 }
like image 149
Dat Nguyen Avatar answered Mar 27 '23 12:03

Dat Nguyen