Scala Guava类型不匹配问题

时间:2018-04-10 16:31:48

标签: scala types guava scala-java-interop google-guava-cache

我正在尝试使用Guava缓存实现一个简单的用例,但面临一些问题,如下所示:

case class Person(x:Int, y:String)
val db = Map(1 -> Person(1,"A"), 2 -> Person(2,"B"), 3 -> Person(3,"C"))

val loader:CacheLoader[Int,Person] = new CacheLoader[Int,Person](){
    def load(key: Int): Person = {
      db(key)
    }
}

lazy val someData = CacheBuilder.newBuilder().expireAfterWrite(60, MINUTES).maximumSize(10).build(loader)

 someData.get(3)

我得到的错误与我无法弄清楚的类型有关

scala> someData.get(3)
<console>:24: error: type mismatch;
    found   : Int(3)
    required: Int
             someData.get(3)     

有人可以就可能出现的问题提出建议。

1 个答案:

答案 0 :(得分:2)

这是Java的使用站点协方差注释的常见问题。

这适用于scala 2.12.4和guava 24.1:

import com.google.common.cache._
import java.util.concurrent.TimeUnit._

object GuavaCacheBuilderTypeProblem {
    case class Person(x:Int, y:String)
    val db = Map(1 -> Person(1,"A"), 2 -> Person(2,"B"), 3 -> Person(3,"C"))

    val loader: CacheLoader[java.lang.Integer, Person] = 
      new CacheLoader[java.lang.Integer, Person](){
        def load(key: java.lang.Integer): Person = {
          db(key)
        }
      }

    lazy val someData = CacheBuilder
      .newBuilder()
      .expireAfterWrite(60, MINUTES)
      .maximumSize(10)
      .build[java.lang.Integer, Person](loader)

    someData.get(3)
}

有类似错误的答案:

  1. compiler error when using Google guava from scala code