I am trying to update an immutable Map in an immutable Map, but that gives me an error:
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)
ERROR:
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))
How can I replace the immutable Map value by a new one in the m
without making m
mutable?
CodePudding user response:
As @Luis Miguel Mejía Suárez noted in the comments, using updated
and updatedWith
methods solved the problem. Example: https://scastie.scala-lang.org/BalmungSan/kdlqN3t5SGiQ26oDPyy0jg/2