简体   繁体   English

Scala中的类到实例多图

[英]Class to Instance Multimap in scala

What's the idiomatic way to have associate Class[T] s to List[T] s? Class[T]关联到List[T]的惯用方式是什么? Essentially, I want the equivalent of Guava's ClassToInstanceMap , but in a Multimap form. 本质上,我想使用Guava的ClassToInstanceMap等效,但是要使用Multimap形式。

I am uncertain about how Scala's mutable.Multimap would fit in here. 我不确定Scala的mutable.Multimap是否适合这里。

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): 标准库中没有任何内容,但是实现起来很简单(使用ClassTag代替Class来稍微简化API):

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 (eg Option[Int] and Option[String] ) separately. 如果要分别存储具有相同类和不同泛型类型参数(例如Option[Int]Option[String] )的实例,请使用TypeTag而不是ClassTag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM