Created
May 19, 2017 12:51
-
-
Save Fristi/37a887fdb956f2602aabd04a433f0b3b to your computer and use it in GitHub Desktop.
Simple EitherT monad transformer example
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.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import scala.concurrent.{Await, Future} | |
import scalaz.Scalaz._ | |
import scalaz._ | |
case class Person(name: String, age: Int, teamId: Int) | |
case class Team(name: String) | |
object Main extends App { | |
def findPersonById(id: Int): Future[Option[Person]] = Future.successful(Some(Person("Mark", 30, 1))) | |
def findTeamById(id: Int): Future[Option[Team]] = Future.successful(None) | |
type Program[A] = EitherT[Future, String, A] | |
def fromValue[A](v: A) = EitherT[Future, String, A](Future.successful(\/-(v))) | |
def fromOption[A](v: Option[A], errMsg: String) = EitherT[Future, String, A](Future.successful(v.fold[String \/ A](-\/(errMsg))(\/-.apply))) | |
def fromFutureOption[A](v: Future[Option[A]], errMsg: String) = EitherT[Future, String, A](v.map(_.fold[String \/ A](-\/(errMsg))(\/-.apply))) | |
val program: Program[Team] = for { | |
person <- fromFutureOption(findPersonById(1), "Person cannot be found") | |
team <- fromFutureOption(findTeamById(person.teamId), "Team cannot be found") | |
} yield team | |
println(Await.result(program.run, 2.seconds)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment