我有以下代码用于使用谷歌集合构建缓存:
val cache = new MapMaker().softValues().expiration(30,
TimeUnit.DAYS).makeComputingMap(
new com.google.common.base.Function[String,Int] {
def apply(key:String):Int ={
1
}
})
我收到以下错误消息:
error: type mismatch;
found : java.lang.Object with
com.google.common.base.Function[java.lang.String,Int]{ ... }
required: com.google.common.base.Function[?, ?]
new com.google.common.base.Function[String,Int] {
^
我想知道为什么类型不匹配?
实际代码是:
import com.google.common.collect.MapMaker
trait DataCache[V] {
private val cache = new MapMaker().softValues().makeComputingMap(
new com.google.common.base.Function[String,V] {
def apply(key:String):V = null.asInstanceOf[V]
})
def get(key:String):V = cache.get(key)
}
亲切的问候,
阿里
PS - 我正在使用 google-collections v1
最佳答案
您需要为最终的方法调用提供类型参数。您正在通过原始类型接口(interface),而 scala 无法重建类型信息。
val cache = new MapMaker().softValues().expiration(30,
TimeUnit.DAYS).makeComputingMap[String, Int](
new com.google.common.base.Function[String,Int] {
def apply(key:String):Int ={
1
}
})
关于scala - 在 Scala 中实现 java 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2162056/