Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Last active February 19, 2019 00:40
  • 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/e863ceef48075ed2dca8c309f8a8dfc3 to your computer and use it in GitHub Desktop.
oop to fp - minimum cake
import cats.syntax.option._
// domain layer -----------------------------------------------------------
import monix.eval.Task
case class Movie(id: Int, title: String)
trait MovieRepo {
def getMovie(id: Int): Task[Option[Movie]]
}
trait UsesMovieRepo {
val movieRepo: MovieRepo
}
trait MovieService extends UsesMovieRepo {
def getMovie(id: Int): Task[Option[Movie]] = movieRepo.getMovie(id)
}
// application layer -------------------------------------------------
val dB = Map[Int, Movie](42 -> Movie(42, "A Movie"))
object MovieRepoImpl extends MovieRepo {
def getMovie(id: Int): Task[Option[Movie]] = Task(dB.get(id))
}
trait MixInMovieRepo {
val movieRepo: MovieRepo = MovieRepoImpl
}
object MovieService extends MovieService with MixInMovieRepo
val program = 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 -------------------------------------------------------
val testMovieService = new MovieService {
val movieRepo = new MovieRepo {
def getMovie(id: Int): Task[Option[Movie]] = Task(Movie(-1, "Test").some)
}
}
val testProgram = testMovieService.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