【发布时间】:2016-06-20 06:20:11
【问题描述】:
这是我之前question的后续:
假设我正在重构这样的函数:
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实现它?
【问题讨论】:
-
为什么还在
check中抛出异常? -
@PeterNeyens 我不想更改
check之外的所有代码。
标签: scala refactoring scalaz scala-cats