scala - 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
}
}
}
解决方案
看来您的 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
}
}
推荐阅读
- blockchain - 如何激活 Substrate GRANDPA 定稿?
- javascript - 如何在 JS 上制作高级选项卡
- php - 在 PHP 的 Quick Books 桌面上使用非库存项目创建发票
- android - 未找到 Gradle 插件
- java - 在特定依赖 IntelliJ 中搜索符号?
- javascript - 在 vuejs 中包含一个外部 css 文件
- sql - 在删除重复值时在一行中聚合证书名称
- ios - iOS 向 WKWebView 公开自定义 API
- php - 在 laravel 中,如何在视图中使用 @if 语句来验证数据库条件,以便它根据条件隐藏/显示一些内容
- c - 了解 x86 上 C 函数中的汇编代码