簡體   English   中英

如何更新 Map 值也是 Scala 中的 Map?

[英]How to update Map value that is also a Map in Scala?

我正在嘗試在不可變的 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))

如何在不使m可變的情況下用m中的新值替換不可變的 Map 值?

正如@Luis Miguel Mejía Suárez 在評論中指出的那樣,使用updatedupdatedWith方法解決了這個問題。 示例: https://scastie.scala-lang.org/BalmungSan/kdlqN3t5SGiQ26oDPyy0jg/2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM