I've a three-level data structure (indentation and line breaks for 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 the innermost data (scores) requires a lot of typing:
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)
}
}
Is there a less verbose way to modify the value of scores ?
I'm a Scala newbie, so all other observations of the code above are also welcome.