【问题标题】:Return codes in ScalaScala 中的返回码
【发布时间】:2013-05-11 10:07:10
【问题描述】:

假设我正在 Scala 中编写一个函数,它返回一个返回码SUCCESSERROR1ERROR2、...(注意与scala.util.Either 不同)

显然,我可以创建一个层次结构来表示返回码,如下所示:

特征返回码
案例对象 Success 扩展 ReturnCode
案例对象 Error1 扩展 ReturnCode
案例对象 Error2 扩展 ReturnCode
...

现在我想知道 Scala 中是否有一个“标准”的惯用解决方案。

【问题讨论】:

  • 你为什么不想使用EitherTry
  • 谢谢。我不知道 scala.util.Try。

标签: scala error-handling return-value


【解决方案1】:

您可以使用Try 来替代Either。 "left" 值固定为 Throwable 并且它是右偏的,这意味着 map/flatMap 等只会在成功时执行,并且异常会保持原样,就像 wirh Some 和 @987654325 @为Option。您可以在块周围使用Try.apply 来捕获非致命异常并将结果包装在Try 中。

【讨论】:

  • 如果我的失败并不总是Throwable 怎么办?在这种情况下我该如何使用Try
  • 在这种情况下,您可以创建自己的异常类型。使用Try 的好处是您可以链接您的操作,然后在最后处理错误。
  • 谢谢。我会考虑的。
【解决方案2】:

你可以使用sealed关键字。

sealed trait ReturnCode
case object Success extends ReturnCode
case object Error1 extends ReturnCode
case object Error2 extends ReturnCode

如果您忘记了某些代码,您会收到警告:

scala> def test(r: ReturnCode) = r match {
     |   case Success => "Success"
     |   case Error1 => "Error1"
     | }
<console>:1: warning: match may not be exhaustive.
It would fail on the following input: Error2
       def test(r: ReturnCode) = r match {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2020-09-19
    • 2020-07-19
    • 2022-01-27
    • 2021-09-16
    • 2012-03-31
    • 2012-08-21
    相关资源
    最近更新 更多