[英]modify scala map values
I has learn scala recently,but I found a question when modify map values. 我最近学习了scala,但是在修改地图值时发现了一个问题。
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. 函数exercise1可以运行。 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]
. 我不确定createMap()
函数返回什么,但是我猜测它返回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
. 如果是这样,则您的代码将失败,因为Map[String, Int]
是不可变的,并且您无法使用此代码newMap(k) = 2 * v
将值重新分配给不可变的map。 You must use mutable.Map[String, Int]
here. 您必须在此处使用mutable.Map[String, Int]
。
Example code (in scala REPL): 示例代码(在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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.