开发者

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

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, va开发者_开发技巧lue: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.


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 :).


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜