There's nothing in the standard library, but it's quite trivial to implement (using ClassTag
s 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 TypeTag
s instead of ClassTag
s if you want to store instances with the same class and different generic type arguments (e.g. Option[Int]
and Option[String]
) separately.