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?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With