我有一個三級的數據結構(縮進和換行的可讀性):如何訪問和地圖地圖的可變地圖更新值
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)
}
}
是否有修改分數的值更簡潔的方式?
我是Scala的新手,所以對上面代碼的所有其他觀察也是受歡迎的。
在這個例子中有效,但如果m(「normal」)(「home」)還沒有被定義,它將不起作用。 – Mark 2016-10-12 00:46:48