我正在尝试使用scala创建通用的LoadingCache,并编写了以下代码-
trait GuavaCache[K, V] {
val maxSize = 1000
val expirationTime = 10
val expirationTimeUnit = TimeUnit.MINUTES
def loadKey(k: K): V
lazy val cache: LoadingCache[K, V] = CacheBuilder.newBuilder()
.maximumSize(maxSize)
.recordStats()
.expireAfterWrite(expirationTime, expirationTimeUnit)
.build(new CacheLoader[K,V] {
override def load(key: K): V = loadKey(key)
})
}
但是无法编译以上代码,它提示错误为-
Error:(18, 6) overloaded method value build with alternatives:
[K1 <: Object, V1 <: Object]()com.google.common.cache.Cache[K1,V1] <and>
[K1 <: Object, V1 <: Object](x$1: com.google.common.cache.CacheLoader[_ >: K1, V1])com.google.common.cache.LoadingCache[K1,V1]
cannot be applied to (com.google.common.cache.CacheLoader[K,V])
.build(new CacheLoader[K,V] {
但是大多数博客文章也建议仅以相同的方式进行操作,https://commitlogs.com/2017/03/11/caching-predictive-models-using-guava-in-scala/
Scala版本-2.12 番石榴版本-“ 27.0-jre”
答案 0 :(得分:0)
该错误使诊断非常困难,但是此修复很简单。您需要声明您的K和V继承自Object(java.lang.object)。因此解决方法很简单:
trait GuavaCache[K <: Object, V <: Object] { ...