How to implement Map with default operation in Scala

Lukasz picture Lukasz · Apr 29, 2011 · Viewed 31.2k times · Source
class DefaultListMap[A, B <: List[B]] extends HashMap[A, B] {
    override def default(key: A) = List[B]() 
  }

I wan't to create map A -> List[B]. In my case it is Long -> List[String] but when I get key from map that doesn't have value I would like to create empty List instead of Exception being thrown. I tried different combinations but I don't know how to make code above pass the compiler.

Thanks in advance.

Answer

Ilya Klyuchnikov picture Ilya Klyuchnikov · Apr 29, 2011

Why not to use withDefaultValue(value)?

scala> val m = Map[Int, List[String]]().withDefaultValue(List())
m: scala.collection.immutable.Map[Int,List[String]] = Map()

scala> m(123)
res1: List[String] = List()