scalatypesguavascala-java-interopgoogle-guava-cache

Scala Guava type mismatch issue


I am trying to implement a simple usecase using Guava caching but facing some issues as shown below:

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)

The error I am getting is related to types which I am not able figure out

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

Can someone advice on what can be the issue.


Solution

  • That's a common issue with Java's use-site covariance annotations.

    This here works with scala 2.12.4 and 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)
    }
    

    Answers with similar errors:

    1. compiler error when using Google guava from scala code