Search code examples
scalaguava

Guava Cache Generic LoadingCache


I am trying to create a generic LoadingCache with scala and have wrote following code -

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)
    })

}

However can't get the above code compiled, it prompts error as -

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] {

However most of the blog posts also suggests doing in the same manner only, https://commitlogs.com/2017/03/11/caching-predictive-models-using-guava-in-scala/

Scala Version - 2.12 Guava Version - "27.0-jre"


Solution

  • The error makes it very difficult to diagnose, but this has a simple fix. You need to declare that your K and V inherit from Object (java.lang.object). So the fix is simply:

    
    trait GuavaCache[K <: Object, V <: Object] { ...