Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access and update a value in a mutable map of map of maps
    primarykey
    data
    text
    <p>I've a three-level data structure (indentation and line breaks for readability):</p> <pre><code>scala&gt; import scala.collection.mutable.Map import scala.collection.mutable.Map scala&gt; val m = Map("normal" -&gt; Map("home" -&gt; Map("wins" -&gt; 0, "scores" -&gt; 0), "away" -&gt; Map("wins" -&gt; 0, "scores" -&gt; 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 -&gt; Map(wins -&gt; 0, scores -&gt; 0), home -&gt; Map(wins -&gt; 0, scores -&gt; 0)))) </code></pre> <p>Accessing the innermost data (scores) requires a lot of typing:</p> <pre><code>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" -&gt; Map("home" -&gt; Map("wins" -&gt; 0, "scores" -&gt; 0), "away" -&gt; Map("wins" -&gt; 0, "scores" -&gt; 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) } } </code></pre> <p>Is there a less verbose way to modify the value of scores ?</p> <p>I'm a Scala newbie, so all other observations of the code above are also welcome.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload