Search code examples
scalamultimap

Scala multimap: get item or else empty set


if I'm using the Scala Multimap, and I want to get the values associated with a key or else the empty set, do I have to write the following?

multimap.getOrElse("key", new collection.mutable.HashSet())

It would seem that the following should just work. An empty set seems like a good default value.

multimap.getOrElse("key")

Solution

  • As you observed, the MultiMap trait doesn't do what you want. However, you can add a default value yourself if the Map is specifically mutable or immutable. Here's an example,

    scala> val m = collection.mutable.Map(1 -> 2)
    m: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)
    
    scala> val m2 = m.withDefaultValue(42)
    m2: scala.collection.mutable.Map[Int,Int] = Map(1 -> 2)
    
    scala> m2(1)
    res0: Int = 2
    
    scala> m2(2)
    res1: Int = 42
    

    Strangely, the above won't work if the type of m is an abstract collection.Map. The comment in the source code says this is due to variance issues.