Scala Guava type mismatch issue

大城市里の小女人 提交于 2019-12-11 10:51:38

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/49758706/scala-guava-type-mismatch-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!