首页 > 解决方案 > Scala中记忆/缓存请求的类型擦除

问题描述

我在 Scala 中收到类型擦除警告。

问题是我需要缓存传出请求。尽管由于当前设置的方式,请求可以包装不同的返回类型。

我试图通过在 getOrPut 方法中添加类型参数来解决它。然而,在 match 语句中,由于类型擦除,Future 中包含的任何内容都不会被检查。

我可以通过使用@unchecked 来消除类型擦除警告,但我想知道是否有更好的方法来确保返回的类型是所需的类型。

简化示例:

class RequestCache() {
  val underlying: scala.collection.mutable.Map[String, Future[Any] =
    scala.collection.mutable.Map()

  def getOrPut[A](
    key: String,
    val: Future[Request[A]]
  ): Future[Request[A]] = {
    underlying.get(key) match {
      case None => { 
        underlying.update(key, val)
        val
      }
      case Some(storedVal: Future[Request[A]]) => storedVal
    }
  }
    
}

标签: scalatypestype-erasure

解决方案


看来您的 Map 值将是 Future[Request[A]]] 类型。为什么不让类RequestCache采用类型参数,并且这种方法不会出现类型擦除问题:

class RequestCache[A] {
  val underlying: scala.collection.mutable.Map[String, Future[Request[A]]] =
    scala.collection.mutable.Map()

  def getOrPut(key: String, value: Future[Request[A]]): Future[Request[A]] =
    underlying.get(key) match {
      case None =>
        underlying.update(key, value)
        value
      case Some(storedVal: Future[Request[A]]) =>
        storedVal
    }
}

推荐阅读