scala泛型的编译问题

Compile issue with scala generics

object PDJcrCache {
  val cache = new ConcurrentHashMap[String, _ <: PDEntity]()

  def put[A <: PDEntity](elem: A) = {
    cache.put(elem.asInstanceOf[PDEntity].getId, ***elem***)
  }
  def get[A <: PDEntity](id: String): A = {
    cache.get(id).asInstanceOf[A]
  }
  def remove[A <: PDEntity](id: String) = {
    cache.remove(id)
  }
}

我在以下位置遇到编译错误 cache.put(elem.asInstanceOf[PDEntity].getId, ***elem***)。 它说 expected _, actual A。关于这个问题的任何想法? 这也是使用 Scala 泛型的正确方法吗?

ConcurrentHashMap[String, _ <: PDEntity] 是一个映射,其值的类型为 "some unknown subtype of PDEntity"。所以你不能将 elem 放入这样的映射中,因为 A 可能是 PDEntity 的不同子类型,与该映射使用的特定子类型不同。

您可能想要一个 ConcurrentHashMap[String, PDEntity],但老实说,您的大多数泛型看起来都是不必要的 - 如果您只想存储和检索 PDEntity,为什么不就这样保留它们呢?如果您想要 PDEntity 的某些特定子类型的缓存,那么 A 应该是 class 上的类型参数,而不是单个方法上的类型参数。你想达到什么目的?