Skip to content

Instantly share code, notes, and snippets.

Last active Apr 25, 2019
What would you like to do?
dependency injection sample with ZIO
import scalaz.zio.{DefaultRuntime, IO, ZIO}
// domain layer -----------------------------------------------------------
sealed trait AppError
case object NoValue extends AppError
case class Movie(id: Int, title: String)
trait MovieRepo {
def getMovie(id: Int): IO[AppError, Movie]
// application layer ----------------------------------------------
val db = Map[Int, Movie](42 -> Movie(42, "A Movie"))
object MovieRepoImpl extends MovieRepo {
def getMovie(id: Int): IO[AppError, Movie] =
trait Env {
val movieRepo: MovieRepo
object Env extends Env {
val movieRepo = MovieRepoImpl
object MovieService {
def getMovie(id: Int): ZIO[Env, AppError, Movie] =
ZIO.environment[Env] >>= (_.movieRepo.getMovie(id))
val program: ZIO[Env, AppError, Movie] = MovieService.getMovie(42)
// runtime layer -------------------------------------------------
new DefaultRuntime {}.unsafeRunSync(program.provide(Env))
// testing layer -------------------------------------------------
import cats.syntax.either._
new DefaultRuntime {}.unsafeRunSync(program.provide(new Env {
val movieRepo = _ => IO.fromEither(NoValue.asLeft)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment