I have been counting occurences with a mutable map:
var bar = collection.mutable.Map[Int, Int]().withDefaultValue(0)
Now bar(a) += b
works just fine, no matter if the key a
is present in bar
already or not (in which case it will then be added).
I tried the same thing with a mutable map of mutable maps:
var foo = collection.mutable.Map[Int, collection.mutable.Map[Int, Int]]().
withDefaultValue(collection.mutable.Map().withDefaultValue(0))
How does foo(a)(b) += x
look without syntactic sugar?
Using What are all the instances of syntactic sugar in Scala? I would assume it expands to:
foo.apply(a).put(b, foo.apply(a).apply(b) + x)
But why does this not update foo
itself accordingly like in the introductory example (i.e. foo
will not have a dedicated value for key a
if it wasn't present before)?
Edit: As Perseids pointed out, foo(a)(b) += x
will change the mutable default value. Is this a desired feature?
Using getOrElseUpdate
as suggested by DaoWen seems to be the best way to overcome both problems. But while that works well for functions of type Int => Int => Int
it becomes really cumbersome for functions of type Int => Int => Int => Int => Int
. So I'm still happy for any suggestions!