scala - How to access and update a value in a mutable map of map of maps -
i've three-level data structure (indentation , line breaks readability):
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))))
accessing innermost data (scores) requires lot of typing:
import org.scalatest.{assertions, funsuite} class mapexamplesso extends funsuite assertions { test("update values in mutable map of map of maps") { import scala.collection.mutable.map // m map accumulator val m = map("normal" -> map("home" -> map("wins" -> 0, "scores" -> 0), "away" -> map("wins" -> 0, "scores" -> 0) ) ) // // there less verbose way increment 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) } }
is there less verbose way modify value of scores ?
i'm scala newbie, other observations of code above welcome.
you don't have use "apply" "()"
m("normal")("home")("scores") = 1
Comments
Post a Comment