[英]Scala Cats OptionT with Either. How to create an error value?
I am working through the excellent Scala with Cats and I'm not sure about Monad transformers. 我正在与Cats一起研究出色的Scala,我不确定Monad变压器。 Specifically, there is an example that goes 具体来说,有一个例子
type ErrorOr[A] = Either[String, A]
type ErrorOrOption[A] = OptionT[ErrorOr, A]
val a = 10.pure[ErrorOrOption] // a: OptionT(Right(Some(10)))
val b = 32.pure[ErrorOrOption] // b: OptionT(Right(Some(32)))
val c = a.flatMap(x => b.map(y => x + y)) // c: OptionT(Right(Some(42)))
How could I create an empty option? 如何创建一个空选项?
// d: OptionT(Right(None))
How could I create an error value? 如何创建错误值?
// e: OptionT(Left("A terrible error."))
Is it correct that if I mapped over those the propagated value would be a Left? 如果我在这些值上映射,则传播的值将为Left是否正确?
Thanks. 谢谢。
I got it, I needed to use apply
. 我明白了,我需要使用apply
。
val e = OptionT[ErrorOr, Int](Right(None))
val d = OptionT[ErrorOr, Int](Left("A terrible error."))
val f = for {
e1 <- d
e2 <- e
} yield e1 + e2 // f: OptionT(Left(A terrible error.))
val g = 10.pure[ErrorOrOption]
val h = OptionT[ErrorOr, Int](Right(None))
val i = for {
e1 <- g
e2 <- h
} yield e1 + e2 // i: OptionT(Right(None))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.