我可以用什么来更好地编写这个 Scala 代码?

The*_*ude 1 scala

functionThatReturnsATry[Boolean]() match {
      case Success(value) =>
        value match {
          case true => somethingThatReturnsFuture[Unit]
          case false =>
            Failure(new SomeException("This failed here"))
        }
      case Failure(exception) => Failure(exception)
    }
Run Code Online (Sandbox Code Playgroud)

functionThatReturnsATry成功完成后,代码将返回 Future[Unit]并返回 true。
如果functionThatReturnsATry失败,我想将失败传递到链条上。
如果functionThatReturnsATry返回 false,我想在链上传递一个新的特定失败

Tim*_*Tim 5

一种改进是在 上使用保护表达式match来分隔三种不同的情况。您还应该返回Future.failed而不是Failure结果Future[Unit]不是Any

functionThatReturnsATry[Boolean]() match {
  case Success(value) if value =>
    somethingThatReturnsFuture[Unit]

  case Success(_) =>
    Future.failed(new SomeException("This failed here"))

  case Failure(exception) =>
    Future.failed(exception)
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用“case Success(true) => ...”。这是关键字,它是按值匹配的。 (3认同)
  • 或者 ```case Success(`true`) =>``` 或者。 (2认同)