我正在为 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] extends CachedEntity[E,Long]
[error] ^
[error] one error found