Question

What's the idiomatic way to have associate Class[T]s to List[T]s? Essentially, I want the equivalent of Guava's ClassToInstanceMap, but in a Multimap form.

I am uncertain about how Scala's mutable.Multimap would fit in here.

Was it helpful?

Solution

There's nothing in the standard library, but it's quite trivial to implement (using ClassTags instead of Class to simplify the API a bit):

class ClassToInstanceMultiMap private (private val delegate: Map[ClassTag[_], List[_]]) {
  def addInstance[T](x: T)(implicit ct: ClassTag[T]) = 
    new ClassToInstanceMultiMap(delegate + (ct -> x))

  def getInstances[T](implicit ct: ClassTag[T]) = delegate.getOrElse(ct, List.empty).asInstanceOf[List[T]]

  // whatever other methods you want
}

object ClassToInstanceMultiMap {
  val empty = new ClassToInstanceMultiMap()
}

// usage
val cimm = ClassToInstanceMultiMap.empty.addInstance(1).addInstance(2).addInstance("a").getInstances[Int]
// returns List(1, 2)

Use TypeTags instead of ClassTags if you want to store instances with the same class and different generic type arguments (e.g. Option[Int] and Option[String]) separately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top