Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active February 19, 2019 00:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yasuabe/48580b18579041b6406ffa07b5cde3ba to your computer and use it in GitHub Desktop.
oop to fp - original cake
import cats.syntax.option._
// domain layer -----------------------------------------------------------
import monix.eval.Task
case class Movie(id: Int, title: String)
trait MovieRepoComponent {
trait MovieRepo {
def getMovie(id: Int): Task[Option[Movie]]
}
}
trait MovieServiceComponent { this: MovieRepoComponent =>
val movieRepo: MovieRepo
class MovieService {
def getMovie(id: Int): Task[Option[Movie]] = movieRepo.getMovie(id)
}
}
// application layer -------------------------------------------------
val db = Map[Int, Movie](42 -> Movie(42, "A Movie"))
trait MovieRepoComponentImpl extends MovieRepoComponent {
class MovieRepoImpl extends MovieRepo {
def getMovie(id: Int): Task[Option[Movie]] = Task(db.get(id))
}
}
object Registry
extends MovieServiceComponent with MovieRepoComponentImpl {
val movieRepo = new MovieRepoImpl
val movieService = new MovieService
}
val program = Registry.movieService.getMovie(42)
// rumtime layer -------------------------------------------------
import scala.concurrent.Await
import monix.execution.Scheduler.Implicits.global
import scala.concurrent.duration._
Await.result(program.runToFuture, 1.second)
// test environment -------------------------------------------------------
trait MovieRepoComponentTestImpl extends MovieRepoComponent {
class MovieRepoTestImpl extends MovieRepo {
def getMovie(id: Int): Task[Option[Movie]] = Task(Movie(-1, "Test").some)
}
}
object TestRegistry
extends MovieServiceComponent with MovieRepoComponentTestImpl {
val movieRepo = new MovieRepoTestImpl
val movieService = new MovieService
}
val testProgram = TestRegistry.movieService.getMovie(42)
Await.result(testProgram.runToFuture, 1.second)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment