Skip to content

Instantly share code, notes, and snippets.

@globulon
Created July 28, 2016 20:26
Show Gist options
  • Select an option

  • Save globulon/98109c436e6e9cb3f9b3e2cc8455b33a to your computer and use it in GitHub Desktop.

Select an option

Save globulon/98109c436e6e9cb3f9b3e2cc8455b33a to your computer and use it in GitHub Desktop.
Type inheritance for KVS injection
import scala.language.higherKinds
//Contract on what can be cached
trait CanBeCached[T]
trait InMemory[T] extends CanBeCached[T]
//Contracts inherited persistable implementations
trait Persistable[T] extends CanBeCached[T]
trait InheritPersistable[T, +R <: InheritPersistable[T, R]] extends Persistable[T] { self: R => }
trait RedisPersistable[T] extends InheritPersistable[T, RedisPersistable[T]] {
def doSomething: T => T
}
trait MemCachePersistable[T] extends InheritPersistable[T, MemCachePersistable[T]] {
def doSomethingElse: T => T
}
//Defines KVS that can be inherited
trait InheritKVS[Key, +C[_] <: CanBeCached[_], +K <: InheritKVS[Key, C, K]] { self : K => }
trait KVS[Key, +C[_] <: CanBeCached[_]] extends InheritKVS[Key, C, KVS[Key, C]]
class RedisKVS extends KVS[String, RedisPersistable]
class MemCacheKVS extends KVS[String, MemCachePersistable]
class InMemoryKVS extends KVS[String, InMemory]
//Defines factory that can be inherited
trait InheritKVSFactory[Key, +C[_] <: CanBeCached[_], +F <: InheritKVSFactory[Key, C, F]] { self: F =>
def makeKVS: KVS[Key, C]
}
trait KVSFactory[Key, +C[_] <: CanBeCached[_]] extends InheritKVSFactory[Key, C, KVSFactory[Key, C]]
//Injection
implicit def PersistentKVSFactory: KVSFactory[String, Persistable] = new KVSFactory[String, Persistable] {
override def makeKVS = new RedisKVS
}
implicit def inMemoryKVSFactory: KVSFactory[String, InMemory] = new KVSFactory[String, InMemory] {
override def makeKVS = new InMemoryKVS
}
implicit def makeKVS[Key, C[_] <: CanBeCached[_]](implicit fact: KVSFactory[Key, C]) : KVS[Key, C] = fact.makeKVS
//test
makeKVS[String, InMemory]
makeKVS[String, Persistable]
// res0: KVS[String,InMemory] = InMemoryKVS@75e91545
// res1: KVS[String,Persistable] = RedisKVS@242aa8d9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment