How to use JCache in Scala? I get compiler type er

2019-08-15 13:46发布

问题:

I'm learning Scala and trying to use javax.cache in Scala code and can't find how to solve this problem:

val cacheFactory = CacheManager.getInstance.getCacheFactory
val map = new HashMap
val cache = cacheFactory.createCache(map)

def rawSet(key:String, value:Array[Byte]) {
    cache.put(key, value)
}

and the compiler error is:

error: type mismatch
found: String
required: K
in cache.put(key, value)

Edit:
As Daniel said, I should have mentioned in the question that I'm over app engine since that seems to be highly relevant. In this case, the solution is to create a small class in Java to do this particular code, and call it from Scala.

回答1:

Try:

val cache: Cache[_, AnyRef] = cacheFactory.getCache(new HashMap[String, AnyRef])

Or even Cache[_, _]. You may have to use something like this to put the values:

cache.asInstanceOf[HashMap[String,AnyRef]].put(key, value)

I'm pretty sure there is a way to do it without asInstanceOf, using the full existential syntax (Cache[T, AnyRef] forSome { type T }), but I can't recall how (or find the site that explains it :).



回答2:

The problem seems to be one of providing the correct generic parameters for the HashMap. I presume you want something like:

val map = new HashMap[String, AnyRef]

Remember: Scala does not allow the use of raw types.

It's probably a good idea to use the REPL to see what type Scala has inferred your cache variable to be, or to provide the type information yourself to see whether it compiles OK:

val cache: Cache[String, AnyRef] = cacheFactory.getCache(map)