这是我之前的问题的后续行动:
假设我正在重构这样的函数:
def check(ox: Option[Int]): Unit = ox match {
case None => throw new Exception("X is missing")
case Some(x) if x < 0 => throw new Exception("X is negative")
case _ => ()
}
我正在编写一个新的纯函数doCheck
来返回一个Unit
或一个异常。
case class MissingX() extends Exception("X is missing")
case class NegativeX(x: Int) extends Exception(s"$x is negative")
import scalaz._, Scalaz._
type Result[A] = Excepiton \/ A
def doCheck(ox:Option[Int]): Result[Unit] = for {
x <- ox toRightDisjunction MissingX()
_ <- (x >= 0) either(()) or NegativeX(x)
} yield ()
然后从check
def check(ox:Option[Int]): Unit = doCheck(ox) match {
case -\/(e) => throw e
case _ => ()
}
是否有意义 ?那样实施会更好doCheck
吗?
def doCheck(ox:Option[Int]): Result[Int] = for {
x1 <- ox toRightDisjunction MissingX()
x2 <- (x1 >= 0) either(x1) or NegativeX(x1)
} yield x2
如何实现它cats
?