我有一个三级数据结构(缩进和换行以提高可读性):
scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map
scala> val m = Map("normal" -> Map("home" -> Map("wins" -> 0, "scores" -> 0),
"away" -> Map("wins" -> 0, "scores" -> 0)))
m: scala.collection.mutable.Map[java.lang.String,
scala.collection.mutable.Map[java.lang.String,
scala.collection.mutable.Map[java.lang.String,Int]]] =
Map((normal,Map(away -> Map(wins -> 0, scores -> 0),
home -> Map(wins -> 0, scores -> 0))))
访问最里面的数据(分数)需要大量输入:
import org.scalatest.{Assertions, FunSuite}
class MapExamplesSO extends FunSuite with Assertions {
test("Update values in a mutable map of map of maps") {
import scala.collection.mutable.Map
// The m map is essentially an accumulator
val m = Map("normal" ->
Map("home" -> Map("wins" -> 0, "scores" -> 0),
"away" -> Map("wins" -> 0, "scores" -> 0)
)
)
//
// Is there a less verbose way to increment the scores ?
//
assert(m("normal").apply("home").apply("scores") === 0)
val s1 = m("normal").apply("home").apply("scores") + 1
m("normal").apply("home").update("scores", s1)
assert(m("normal").apply("home").apply("scores") === 1)
val s2 = m("normal").apply("home").apply("scores") + 2
m("normal").apply("home").update("scores", s2)
assert(m("normal").apply("home").apply("scores") === 3)
}
}
有没有更简洁的方法来修改 score 的值?
我是 Scala 新手,因此也欢迎对上述代码的所有其他观察。