How to use JCache in Scala? I get compiler type error: found String required K

丶灬走出姿态 提交于 2019-12-11 06:39:18

问题


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)


来源:https://stackoverflow.com/questions/1657494/how-to-use-jcache-in-scala-i-get-compiler-type-error-found-string-required-k

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