tags:

views:

1013

answers:

2
+3  Q: 

Multimap in Scala

I'm trying to mixin the MultiMap trait with a HashMap like so:

val children:MultiMap[Integer, TreeNode] = 
    new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]

The definition for the MultiMap trait is:

trait MultiMap[A, B] extends Map[A, Set[B]]

Meaning that a MultiMap of types A & B is a Map of types A & Set[B], or so it seems to me. However, the compiler complains:

C:...\TestTreeDataModel.scala:87: error: illegal inheritance;
template $anon inherits different type instances of trait Map:
scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found

It seems that generics are tripping me up again.

+5  A: 

I had to import scala.collection.mutable.Set. It seems the compiler thought the Set in HashMap[Integer, Set[TreeNode]] was scala.collection.Set. The Set in the MultiMap def is scala.collection.mutable.Set.

sblundy
+8  A: 

That can be annoying, the name overloading in Scala's collections is one of its big weaknesses.

For what it's worth, if you had scala.collections._ imported, you could probably have written your HashMap type as:

new HashMap[ Integer, mutable.Set[ TreeNode ] ]
Calum