我不想写很多样板代码,所以我决定为惰性初始化编写通用方法。
import java.util._
import concurrent.ConcurrentHashMap
object GenericsTest {
val cache: ConcurrentHashMap[Long,
ConcurrentHashMap[Long,
ConcurrentHashMap[Long,
ConcurrentHashMap[Long, Long]]]] = new ConcurrentHashMap()
def main(args: Array[String]) {
val x = get(cache, 1)(() => new ConcurrentHashMap())
val y = get(x, 1)(() => new ConcurrentHashMap())
val z = get(y, 1)(() => new ConcurrentHashMap())
}
def get[B, A](map: ConcurrentHashMap[A, B], a: A)(factory: () => B): B = {
if (map.containsKey(a)) {
map.get(a)
} else {
val b = factory()
map.put(a, factory())
b
}
}
}
此示例仅使用硬编码Long而不是通用A运行,这可能是什么问题?也许还有另一种方法可以做这些事情?