深圳scala-meetup-20180902(3)- Using heterogeneous Monads in for-comprehension with Monad Transformer
阿新 • • 發佈:2018-12-12
object session41 extends App {
type DBOError[A] = EitherT[Task,String,A]
type DBOResult[A] = OptionT[DBOError,A]
def valueToDBOResult[A](a: A) : DBOResult[A] =
Applicative[DBOResult].pure(a)
def optionToDBOResult[A](o: Option[A]): DBOResult[A] =
OptionT(o.pure[DBOError])
def eitherToDBOResult[A](e: Either[String,A]): DBOResult[A] = {
val error: DBOError[A] = EitherT.fromEither[Task](e)
OptionT.liftF(error)
}
def taskToDBOResult[A](task: Task[A]): DBOResult[A] = {
val error: DBOError[A] = EitherT.liftF[Task,String,A](task)
OptionT.liftF(error)
}
def task[T](t: T): Task[T] = Task.delay(t)
def add(a: Int, b: Int): Task[Int] = Task.delay(a + b)
val calc: DBOResult[Int] = for {
a <- valueToDBOResult(10)
b <- optionToDBOResult(Some(3)) //None: Option[Int])
c <- eitherToDBOResult(Left[String,Int]("oh my good ..."))
d <- taskToDBOResult(add(b,c))
} yield d
val sum: Task[Either[String,Option[Int]]] = calc.value.value
import monix.execution.Scheduler.Implicits.global
import scala.util._
sum.runOnComplete {
case Success(s) => println(s"DBOResult sum=$s")
case Failure(exception) => println(exception.getMessage)
}
}
//DBOResult sum=Left(oh my good ...)