Last active
August 29, 2015 14:06
-
-
Save gigiigig/c6aba7e4ece3e1462179 to your computer and use it in GitHub Desktop.
Type class DI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.language.higherKinds | |
import scala.language.implicitConversions | |
import scalaz._ | |
import Scalaz._ | |
import shapeless._ | |
object console { | |
case class ServiceA(name: String) | |
case class ServiceB(name: String, sa: ServiceA) | |
object Dependencies { | |
trait Dependency[T] { | |
def get: T | |
} | |
implicit def extract[T : Dependency](t: Dependency[T]): T = implicitly[Dependency[T]].get | |
object Dependency { | |
implicit val serviceA = new Dependency[ServiceA] { | |
def get: ServiceA = new ServiceA("serviceA") | |
} | |
implicit def serviceB(implicit serviceA: Dependency[ServiceA]) = new Dependency[ServiceB] { | |
def get: ServiceB = new ServiceB("serviceB", serviceA) | |
} | |
} | |
} | |
import Dependencies._ | |
object App { | |
def printA(implicit serviceA: Dependency[ServiceA]) = { | |
println(s"${serviceA.name}") | |
} | |
def printB(implicit serviceB: Dependency[ServiceB]) = { | |
println(s"${serviceB.name}") | |
} | |
} | |
App.printA | |
App.printB | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment