【问题标题】:What can i use to write this scala code better?我可以用什么来更好地编写这个 scala 代码?
【发布时间】:2020-03-15 16:59:20
【问题描述】:
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)
    }

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

【问题讨论】:

    标签: scala


    【解决方案1】:

    一项改进是在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)
    }
    

    【讨论】:

    • 或者case Success(`true`) =>
    • 您可以使用case Success(true) => ...。这是关键字,按值匹配。
    【解决方案2】:

    我喜欢现有的答案,但作为替代方案,如果您不关心控制第一步的精确异常,您可以将 Try 包装在 Future 中并使用 for-comprehension :

    def attempt(): Try[Boolean] = Success(true)
    def soon(): Future[Unit] = Future.failed(new RuntimeException("uh"))
    
    for {
      success <- Future.fromTry(attempt()) if success
      result <- soon()
    } yield result
    

    代码在here on Scastie可用。

    【讨论】:

      【解决方案3】:

      我很想fold() 而不是Try

      functionThatReturnsATryBool()
        .fold(Future.failed
             ,if (_) somethingThatReturnsFutureUnit()
              else Future.failed(new SomeException("This failed here"))
             )
      

      结果为@​​987654324@ 类型,其中任一类型的失败返回为Future(Failure(java.lang.Exception(...)))。不会丢失错误消息。

      【讨论】:

        【解决方案4】:
        functionThatReturnsATry[Boolean]() match {
          case Success(true) => somethingThatReturnsFuture[Unit]
          case Success(false) => Future.failed(new SomeException("This failed here"))
          case Failure(exception) => Future.failed(exception)
        }
        

        https://scalafiddle.io/sf/DSaGvul/0

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-14
          • 2014-05-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多