gpt4 book ai didi

scala - 尝试并 getOrElse Scala

转载 作者:行者123 更新时间:2023-12-02 05:36:21 26 4
gpt4 key购买 nike

val label = Try("here_a").getOrElse("here_b")

here_a 的情况下没有找到,这不是回退到 here_b .为什么是 .getOrElse无法正常运行?

谢谢@jwvh。这些值是 sting 文件路径,因此异常(exception)是以下 Exception in thread "main" java.io.FileNotFoundException:
根据 Andrew James Ramirez 的评论,我尝试了此操作,但问题仍然存在。
Try(throw new Exception("FAIL here_a")).getOrElse("here_b")
我也试过
Try(throw new Exception("FileNotFoundException here_a")).getOrElse("here_b")
编辑

看来我可能把这个问题过于简单化了。更多的上下文。该字符串实际上是一个文件路径。也许这会有所作为?

实际上,一个 json文件可以在两个可能的位置之一中找到。因此,我希望尝试第一个位置,如果是 java.io.FileNotFoundException返回,退回到第二个位置。这是我目前拥有的:
val input_file = Try(throw new Exception("FAIL location_a/file_a.json")).getOrElse("location_b/file_a.json")
编辑 V2

我不好意思说我发现了简单的错误。我在 spark 上运行此 Scala 代码我忘了在测试之间重新打包。 sbt package这就是所需要的。 :-/

最佳答案

我想你误解了尝试。和 .getOrElse

尝试的定义:

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala.util.Either type.


scala> Try("here_a")
res1: scala.util.Try[String] = Success(here_a)

scala> Try("here_a").get
res2: String = here_a

scala> Try(throw new Exception("FAIL here_a")).getOrElse("here_b")
res3: String = here_b

scala>

只有在抛出异常时才会失败。 null 仍然是一个值。

关于scala - 尝试并 getOrElse Scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40212369/

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