9

在线搜索答案给出了两个突出的帖子(CodacyDaniel Westheide 的),并且都给出了与Scala 的 Try 官方文档相同的答案:

上面示例中显示的 Try 的一个重要属性是它能够管道或链接操作,并在此过程中捕获异常。

上面引用的例子是:

import scala.io.StdIn
import scala.util.{Try, Success, Failure}

def divide: Try[Int] = {
  val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt)
  val divisor = Try(StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt)
  val problem = dividend.flatMap(x => divisor.map(y => x/y))
  problem match {
    case Success(v) =>
      println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
      Success(v)
    case Failure(e) =>
      println("You must've divided by zero or entered something that's not an Int. Try again!")
      println("Info from the exception: " + e.getMessage)
      divide
  }
}

但是我可以使用常规try块轻松地进行流水线操作:

def divideConventional: Int = try {
  val dividend = StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt
  val divisor = StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt
  val problem = dividend / divisor
  println("Result of " + dividend + "/"+ divisor +" is: " + problem)
  problem
} catch {
  case (e: Throwable) =>
    println("You must've divided by zero or entered something that's not an Int. Try again!")
    println("Info from the exception: " + e.getMessage)
    divideConventional
}

(注意:在行为dividedivideConventional略有不同,后者在出现问题的第一个迹象时会出错,但仅此而已。尝试输入“10a”作为输入以dividend了解我的意思。)

我试图看到scala.util.Try的流水线优势,但对我来说,这两种方法似乎是平等的。我错过了什么?

4

1 回答 1

8

我认为您很难看到 的组合能力,Try[T]因为在这两种情况下您都在本地处理异常。如果您想divideConventional使用额外的操作进行组合怎么办?

我们有一些像:

def weNeedAnInt(i: Int) = i + 42

然后我们会有类似的东西:

weNeedAnInt(divideConventional())

但是假设你想最大化你允许用户输入的重试次数(这通常是你在现实生活中的场景,你不能永远重新输入一个方法?我们必须另外包装用 a调用weNeedAnInt自身try-catch

try {
  weNeedAnInt(divideConventional())
} catch {
   case NonFatal(e) => // Handle?
}

但是如果我们使用divide, 并且假设它没有在本地处理异常并向外传播内部异常:

def yetMoreIntsNeeded(i: Int) = i + 64

val result = divide.map(weNeedAnInt).map(yetMoreIntsNeeded) match {
  case Failure(e) => -1
  case Success(myInt) => myInt
}

println(s"Final output was: $result")

这不是更简单吗?也许,我认为这对答案有一定的主观性,我觉得它更干净。想象一下,我们有很长的此类操作的管道,我们可以将每个操作组合Try[T]到下一个,并且只有在管道完成时才担心问题。

于 2016-11-28T07:14:36.560 回答