I am trying to emulate a defaultdict(list) in Scala (I've already declared scala.collection.mutable.HashMap).
Right now I am trying
val d = new HashMap[Int,ListBuffer[Int]](){ override def default(key:Int) = ListBuffer[Int]() }
And then to append to a list I try something like:
d(integerKey) += integerValToInsertIntoList
But nothing seems to work and d
acts like it's always empty?
Here is the proper way of implementing this for mutable Maps:
Note
Using
withDefaultValue
does not work as expected for mutable Maps. It will reuse the same "default" ListBuffer() for all new entries.In the REPL we see that d(4) (same for d(5)) will hold both new added entries: