Knows Not Much Knows Not Much - 4 months ago 20
Scala Question

Scala Maps getOrElseUpdate and Append result

I have a Map which looks like this

var map = Map[Int, Map[Int, Int]]()

I need the functionality where I need to lookup values in the inner map and if the value is found the result is "added" and not just updated.

I have written this code like

map.get(x) match {
case Some(innerMap) =>
innerMap.get(y) match {
case Some(z) => map(x)(y) = z + a
case None => map(x)(y) = z
case None => map(x) = Map(y -> a)

If you pass the inputs
to the code above the map will contain
because values are added.

But I don't like this nested pattern matching. (reminds me of the nested ifs) I tried to simplify this using

.getOrElseUpdate(x, Map(y -> a))
.getOrElseUpdate(y, a)

This is good but doesn't handle the scenario where y in found in the inner map and we needed to do a
z + a


Not necessarily the most efficient solution, but simple - you can instantiate values with zeroes, and then add the value itself assuming all the keys are already there:

  .getOrElseUpdate(x, Map(y -> 0))
  .getOrElseUpdate(y, 0)
map(x)(y) += a