由于在检索缓存时提供类型信息,因此无需尝试和维护通配符键入。将值键入AnyRef然后在结尾处将V形式转换为V要简单得多。以下编译并应该有所帮助。此外,没有必要直接调用asScalaConcurrentMap,因为它很好...隐式。
import scala.collection.JavaConversions._ import com.google.common.collect.MapMaker import java.util.concurrent.TimeUnit import com.google.common.cache.CacheBuilder import scala.collection.mutable.ConcurrentMap trait CacheListener // not sure what this is doing yet. trait CacheManager { def getCache[V <: AnyRef]( cacheName: String, cacheListener: Option[CacheListener] = None): ConcurrentMap[String, V] } class LocalCacheManager extends CacheManager { private val caches: ConcurrentMap[String, ConcurrentMap[String, AnyRef]] = new MapMaker().concurrencyLevel(4).makeMap[String, ConcurrentMap[String, AnyRef]]() def getCache[V <: AnyRef](cacheName: String, cacheListener: Option[CacheListener] = None) = caches.getOrElseUpdate(cacheName, { CacheBuilder.newBuilder() .concurrencyLevel(4) .softValues() .expireAfterAccess(30, TimeUnit.MINUTES) .asInstanceOf[CacheBuilder[String, AnyRef ]] .build[String, AnyRef ]() .asMap() }).asInstanceOf[ConcurrentMap[String, V]] }