条件成立时在Scala中链接多个功能

时间:2019-05-11 18:30:02

标签: scala functional-programming

假设我们有3种方法都返回一个Option

import scala.util.Try

def divideSafe(d: Int): Option[Int] = Try(42 / d).toOption
def sqrtSafe(x: Double): Option[Double] = if(!math.sqrt(x).isNaN) Some(math.sqrt(x)) else None
def convertSafe(s: String): Option[Int] = Try(s.toInt).toOption

现在,我想在条件成立时将它们链接起来。就我而言,如果定义了前一个方法的结果,则应转到下一个方法。只要条件为假,就停止操作并返回默认值。

我可以使用嵌套的if-else语句获得所需的结果:

def superSafe(d: Int, x: Double, s: String): Unit = {
  if (divideSafe(d).isDefined) {
    println(divideSafe(d).get.toString)
    if (sqrtSafe(x).isDefined) {
      println(sqrtSafe(x).toString)
      if (convertSafe(s).isDefined) {
        println(convertSafe(s).get.toString)
      } else {
        println("Converting failed")
      }
    } else {
      println("Sqrt failed")
    }
  } else {
    println("Dividing failed")
  }
}

因此:

superSafe(1, -1, "5")将打印42并且Sqrt失败 superSafe(0, 4, "cat")将打印除法失败 superSafe(42, 4, 1)将打印1,2,1

但是我想避免嵌套的if-else语句,我很想知道Scala中是否存在一种解决此类问题的功能方法。

我想要类似orElse的语句,但是反之。

所需的功能可以这样使用:

divideSafe(42) ifThen("Dividing failed") sqrtSafe(-4) ifThen("Sqrt failed") convertSafe("cat") ifThen("Converting failed")

2 个答案:

答案 0 :(得分:6)

您使用的Option并非最适合您的用例。我相信Either在您的示例中会更好,因为它可以保存有关失败(Left)或成功(Right)的信息。如果您重写函数以使用Either,则可能看起来像这样:

def divideSafe(d: Int): Either[String, Int] = Try(42 / d).toOption.toRight("Divide failed")
def sqrtSafe(x: Double): Either[String, Double] = math.sqrt(x) match {
   case s if s.isNaN => Left("Sqrt failed") //you can use pattern matching to calculate square just once
   case s => Right(s)
} 
def convertSafe(s: String): Either[String, Int] = Try(s.toInt).toOption.toRight("Converting failed")

然后您可以在for comprehension方法中使用superSafe

def superSafe(d: Int, x: Double, s: String): Unit = {
  val r: Either[String, (Int, Double, Int)] = for { //for-comprehension shortcircuits
    r1 <- divideSafe(d) //if divideSafe fails it whole comprehension will return Left(Divide failed)
    r2 <- sqrtSafe(x) //if it succeds it will go further
    r3 <- convertSafe(s)
  } yield (r1,r2,r3)

  r match { 
    case Right((r1,r2,r3)) => { //you could move it inside yield, I splitted it for clarity
      println(r1)
      println(r2)
      println(r3)
    }
    case Left(e) => println(e)
  }
}

答案 1 :(得分:0)

如果您希望它更实用,可以尝试以下操作:

import scala.util.Try

def divideSafe(d: Int): Option[Int] = Try(42 / d).toOption
def sqrtSafe(x: Double): Option[Double] = if(!math.sqrt(x).isNaN) Some(math.sqrt(x)) else None
def convertSafe(s: String): Option[Int] = Try(s.toInt).toOption

def superSafe(d: Int, x: Double, s: String): Any = {
  divideSafe(d)
    .map(rd => sqrtSafe(x)
    .map(rx => convertSafe(s)
    .map(rs => (rd, rx, rs))
    .getOrElse((rd, rx, "Converting failed")))
    .getOrElse((rd, "Sqrt failed")))
    .getOrElse("Dividing failed")
}

println(superSafe(1, 1, "1"))