加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala 2.10类型不匹配使用谷歌番石榴的CacheBuilder

发布时间:2020-12-16 10:02:55 所属栏目:安全 来源:网络整理
导读:我正在为 scala 2.10.1中的一些实体编写通用缓存.目前,我正在使用google Guava的CacheBuilder,因为scala生态系统中的选项不多. 码: trait CachedEntity[E : KeyedEntity[K],K] { def lookup(id:K):E def getElem(id:K):Option[E] = Try(elemCache.get(id)).
我正在为 scala 2.10.1中的一些实体编写通用缓存.目前,我正在使用google Guava的CacheBuilder,因为scala生态系统中的选项不多.

码:

trait CachedEntity[E <: KeyedEntity[K],K] {

  def lookup(id:K):E

  def getElem(id:K):Option[E] = Try(elemCache.get(id)).toOption

  val elemCache = CacheBuilder.newBuilder().maximumSize(10).expireAfterWrite(1,TimeUnit.MINUTES).build(
    new CacheLoader[K,E] {
      def load(key:K) = {
        println("Looking Up key:" + key + "in Class:" + this.getClass.getName)
        lookup(key)
      }
    }
  )
}
trait LongKeyed[E<: KeyedEntity[Long],Long] extends CachedEntity[E,Long]

但是,sbt会抛出错误:

[error] KEHCaching.scala:16: type mismatch;
[error]  found   : id.type (with underlying type K)
[error]  required: Object with K
[error]   def getElem(id:K):Option[E] = Try(elemCache.get(id)).toOption
[error]                                                   ^
[error] one error found

有任何想法吗?即使我像这样添加K<:Object:

trait CachedEntity[E <: KeyedEntity[K],K <:Object] {

我收到这个错误

[error] KEHCaching.scala:27: type arguments [E,Long] do not conform to trait CachedEntity's type parameter bounds [E <: org.squeryl.KeyedEntity[K],K <: Object]
[error] trait LongKeyed[E<: KeyedEntity[Long],Long]
[error]                                                     ^
[error] one error found

解决方法

如果你不介意一点丑陋的演员,你可以让它工作.主要问题是CacheBuilder上的构建函数返回与类型[Object,Object]相关联的缓存.在Scala中,AnyVal不是从Object派生的,因此它不起作用.但是我嘲笑了下面的代码示例,以展示如何通过一些丑陋的转换来解决这个限制:

trait CachedEntity[E <: KeyedEntity[K],K] {

  def lookup(id:K):E

  def getElem(id:K):Option[E] = Try(elemCache.get(id)).toOption

  val elemCache = CacheBuilder.newBuilder().build(
    new CacheLoader[K,E] {
      def load(key:K) = {
        println("Looking Up key:" + key + "in Class:" + this.getClass.getName)
        lookup(key)
     }
    }
  ).asInstanceOf[LoadingCache[K,E]]
}

trait LongKeyed[E<: KeyedEntity[Long]] extends CachedEntity[E,Long]

case class MyEntity(id:Long,value:String) extends KeyedEntity[Long]

class MyEntityCache extends LongKeyed[MyEntity]{
  def lookup(id:Long) = MyEntity(id,"foo") 
}

object CachedEntityTest{
  def main(args: Array[String]) {
    val cache = new MyEntityCache
    val entity = cache.getElem(1)
    println(entity)
  }
}

//Faking this for purposes of code sample...
trait KeyedEntity[K]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读