I need to update (retrieve and increase) two different values bound to two keys in a map. The two keys can coincide sometimes. I have the following code for now:
// val map: Map[Int, Int]
// val key1, key2: Int
if (key1 == key2) {
tailRecFunction(someArg, map
+ Tuple2(key1, 2 + map.getOrElse(key1, 0)))
} else {
tailRecFunction(someArg, map
+ Tuple2(key1, 1 + map.getOrElse(key1, 0))
+ Tuple2(key2, 1 + map.getOrElse(key2, 0)))
}
As you can see, if you use the else
block when key1 == key2
, then the value at key1 == key2
will incorrectly be increased by 1
instead of 2
--- the second tuple erroneously updates the original value, rather than the value applied by the first tuple.
Is there a cleaner way to write this?