views:

190

answers:

1

In Scala I would like to be able to write

val petMap = ImmutableMultiMap(Alice->Cat, Bob->Dog, Alice->Hamster)

The underlying Map[Owner,Set[Pet]] should have both Map and Set immutable. Here's a first draft for ImmutibleMultiMap with companion object:

import collection.{mutable,immutable}

class ImmutableMultiMap[K,V] extends immutable.HashMap[K,immutable.Set[V]]

object ImmutableMultiMap {
  def apply[K,V](pairs: Tuple2[K,V]*): ImmutableMultiMap[K,V] = {
    var m = new mutable.HashMap[K,mutable.Set[V]] with mutable.MultiMap[K,V]
    for ((k,v) <- pairs) m.addBinding(k,v)
    // How do I return the ImmutableMultiMap[K,V] corresponding to m here?
  }
}

Can you resolve the comment line elegantly? Both the map and the sets should become immutable.

Thanks!

+1  A: 

You have a bigger problem than that, because there's no method in ImmutableMultiMap that will return an ImmutableMultiMap -- therefore it is impossible to add elements to it, and the constructor does not provide support for creating it with elements. Please see existing implementations and pay attention to the companion object's builder and related methods.

Daniel
Thanks Daniel. I did try and decipher the builder stuff, by walking through the source code for the companion object to immutable.HashSet. However, I cannot make sense of it.Would you mind showing me how you would solve the problem of constructing the desired ImmutableMultiMap?
PerfectTiling