Knows Not Much Knows Not Much - 2 months ago 7
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
x=2,y=2,a=10
and
x=2,y=2,a=10
to the code above the map will contain
x=2,y=2,a=20
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


map
.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

Answer

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:

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