我正在嘗試在不可變 Map 中更新不可變 Map,但這給了我一個錯誤:
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))
如何在不可變的情況下用新的 Map 值替換不可變的 Mapm值m?
uj5u.com熱心網友回復:
正如@Luis Miguel Mejía Suárez 在評論中指出的那樣,使用updated和updatedWith方法解決了這個問題。示例: https ://scastie.scala-lang.org/BalmungSan/kdlqN3t5SGiQ26oDPyy0jg/2
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444252.html
