如何更新在 Scala 中也是 Map 的 Map 值?
How to update Map value that is also a Map in Scala?
我正在尝试更新不可变映射中的不可变映射,但这给了我一个错误:
var m: immutable.Map[Int, immutable.Map[String, Int]] = Map[Int, immutable.Map[String, Int]]()
val item = Map[String, Int]("Test" -> 0)
m += (1, item)
val newVal: Int = m(1)("Test") + 1
val newValMap = Map[String, Int]("Test"-> newVal)
// This gives an error
m += (1, newValMap)
错误:
value += is not a member of scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,Int]]
Expression does not convert to assignment because:
type mismatch;
found : Int
required: (Int, scala.collection.immutable.Map[String,Int])
type mismatch;
found : (String, Int)
required: (Int, scala.collection.immutable.Map[String,Int])
expansion: TestClass.this.m = TestClass.this.m.+(<1: error>, "Test".$minus$greater(1))
m += (1, ("Test" -> 1))
如何在不使 m
可变的情况下用 m
中的新值替换不可变的 Map 值?
正如@Luis Miguel Mejía Suárez 在评论中指出的那样,使用 updated
和 updatedWith
方法解决了问题。示例:https://scastie.scala-lang.org/BalmungSan/kdlqN3t5SGiQ26oDPyy0jg/2
我正在尝试更新不可变映射中的不可变映射,但这给了我一个错误:
var m: immutable.Map[Int, immutable.Map[String, Int]] = Map[Int, immutable.Map[String, Int]]()
val item = Map[String, Int]("Test" -> 0)
m += (1, item)
val newVal: Int = m(1)("Test") + 1
val newValMap = Map[String, Int]("Test"-> newVal)
// This gives an error
m += (1, newValMap)
错误:
value += is not a member of scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,Int]]
Expression does not convert to assignment because:
type mismatch;
found : Int
required: (Int, scala.collection.immutable.Map[String,Int])
type mismatch;
found : (String, Int)
required: (Int, scala.collection.immutable.Map[String,Int])
expansion: TestClass.this.m = TestClass.this.m.+(<1: error>, "Test".$minus$greater(1))
m += (1, ("Test" -> 1))
如何在不使 m
可变的情况下用 m
中的新值替换不可变的 Map 值?
正如@Luis Miguel Mejía Suárez 在评论中指出的那样,使用 updated
和 updatedWith
方法解决了问题。示例:https://scastie.scala-lang.org/BalmungSan/kdlqN3t5SGiQ26oDPyy0jg/2