gpt4 book ai didi

scala - 与try..catch相比,scala.util.Try有什么优势?

转载 作者:行者123 更新时间:2023-12-04 11:48:35 26 4
gpt4 key购买 nike

在线搜索答案给出了两个突出的帖子(Codacy'sDaniel Westheide's),并且都给出了与Scala's official documentation for Try相同的答案:

An important property of Try shown in the above example is its ability to pipeline, or chain, operations, catching exceptions along the way.



上面引用的示例是:
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的流水线优势,但对我来说,这两种方法似乎是平等的。我想念什么?

最佳答案

我认为您很难看到Try[T]的编写功能,因为这两种情况都是在本地处理异常。如果您想通过其他操作来组成divideConventional怎么办?

我们会有一些像:

def weNeedAnInt(i: Int) = i + 42

然后我们会有类似的东西:
weNeedAnInt(divideConventional())

但是,假设您要最大化允许用户输入的重试次数(通常是您在现实生活中无法永久重新输入方法的情况?我们必须另外包装用 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]组合到下一个,并且仅在管道完成后才担心这些问题。

关于scala - 与try..catch相比,scala.util.Try有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com