如何在不使用 var 的情况下添加到不可变地图?如何将不可变绑定到新值?尝试以下代码时出现错误:
"reassignment to val"
我的代码:
object Play {
def main(args: Array[String]): Unit = {
test1()
}
def test1() {
val pairs = Array(("a", 1), ("b", 2), ("c", 3), ("d", 4))
val m = Map[String, Int]()
for (x <- pairs) {
m = addToMap (x, m)
}
}
def addToMap(pair: (String, Int), map: Map[String, Int]): Map[String, Int] = {
map + (pair._1 -> pair._2)
}
}