Search code examples
listscalahashmapoverridingdefault

Scala HashMap of Lists: simpler default?


I need a HashMap of Lists. Normally I do this:

val lists = mutable.HashMap[String,List[Int]]() { 
  override def default(key: String) = {
    val newList = List[Int]()
    this(key) = newList
    newList
  }
}

so that I can then simply write things like

lists("dog") ::= 14

without having to worry about whether the "dog" List has been initialised yet.

Is there a cleaner way to do this? I find myself typing out those five default override lines again and again.

Thanks!


Solution

  • What about withDefaultValue()?

    val lists = new mutable.HashMap[String,List[Int]].withDefaultValue(Nil)
    
    lists("dog") ::= 13
    lists("cat") ::= 14
    lists("dog") ::= 15  //(13, 15)
    

    See also