I didn't want to write alot of boilerplate code, so I decided to write generic method for lazy-init.
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
}
}
}
This example is only running with hard-coded Long but not with generic A, what can be the problem? Maybe there is another way to do such things?