【发布时间】:2013-04-24 15:39:05
【问题描述】:
我正在为 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
【问题讨论】:
-
如果代码 sn-ps 在语法上是正确的,那将是最好的。无法编译代码中的两个连续句点 (
.)。此外,您的代码 suggests 但没有明确指出K和E是绑定在某些封闭结构中的类型参数。您能否更正和完善代码片段,以便人们复制和修改您的原始代码? -
对不起。也用类声明更新了代码。