Dies ist ein Follow-up zu meinem vorherigen question wirft:Wie eine Funktion, Refactoring, die Ausnahmen mit Scalaz oder Katzen
nehme an, ich bin Refactoring eine Funktion wie folgt aus:
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 _ =>()
}
Ich schreibe ein neue reine Funktion doCheck
, um entweder Unit
oder eine Ausnahme zurückzugeben.
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()
und rufen Sie es dann von check
def check(ox:Option[Int]): Unit = doCheck(ox) match {
case -\/(e) => throw e
case _ =>()
}
Ist es sinnvoll? Wäre es besser, doCheck
so zu implementieren?
def doCheck(ox:Option[Int]): Result[Int] = for {
x1 <- ox toRightDisjunction MissingX()
x2 <- (x1 >= 0) either(x1) or NegativeX(x1)
} yield x2
Wie es mit cats
implementieren?
Warum Sie immer noch die Ausnahme in 'check' werfen? –
@PeterNeyens Ich möchte nicht den gesamten Code außerhalb 'check' ändern. – Michael