Skip to content

Instantly share code, notes, and snippets.

@Fristi
Created May 19, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fristi/37a887fdb956f2602aabd04a433f0b3b to your computer and use it in GitHub Desktop.
Save Fristi/37a887fdb956f2602aabd04a433f0b3b to your computer and use it in GitHub Desktop.
Simple EitherT monad transformer example
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