Skip to content

Instantly share code, notes, and snippets.

@rmihael
Created September 25, 2013 06:20
Show Gist options
  • Save rmihael/6695790 to your computer and use it in GitHub Desktop.
Save rmihael/6695790 to your computer and use it in GitHub Desktop.
trait GenericCache[Key, Value] {
def retrieve(key: Key): Value
def insert(key: Key, value: Value): Unit
}
case class FastCache[Key, Value]() extends GenericCache[Key, Value] {
private var m = Map[Key, Value]() //excuse mutability for illustration purposes
def retrieve(key: Key): Value = m(key)
def insert(key: Key, value: Value) {
m = m + (key -> value)
}
}
case class SlowCache[Key, Value]() extends GenericCache[Key, Value] {
private var m = Map[Key, Value]() //excuse mutability for illustration purposes
def retrieve(key: Key): Value = {
Thread.sleep(1000)
m(key)
}
def insert(key: Key, value: Value) {
Thread.sleep(1000)
m = m + (key -> value)
}
}
object Test {
def test() {
val fc: FastCache[String, Int] = useCache("a", 1, FastCache[String, Int]())
val sc: SlowCache[Char, Int] = useCache('b', 2, SlowCache[Char, Int]())
}
def useCache[Key, Value, Cache <: GenericCache[Key, Value]](a: Key, b: Value, cache: Cache): Cache = {
cache.insert(a, b)
println("getting " + cache.retrieve(a))
cache
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment