【问题标题】:How to graciously combine results from two Either's如何优雅地结合两个 Either 的结果
【发布时间】:2020-06-16 10:49:15
【问题描述】:

我有一个函数,我需要在其中组合来自两个 Either 对象的结果。

如果“handlingResult”是Right,我需要“request”的右侧,并且如果“handlingResult”是Right,“request”也是Right,这是一个既定事实。

如果“handlingResult”为左,我需要它的值来构建响应。

现在这是实现(FailingResponse 和 SuccessResponse 都扩展了 ValuationResponse):

def getResponse(handlingResult : Either[FailureReason, List[StockValuation]]
               ,request        : Either[Error, ValuationRequest]
               ): ValuationResponse = {

  handlingResult.fold(
      failureReason =>
          FailingResponse(failureReason.message
                         ,failureReason.statusCode),
      listOfValuations =>
          SuccessfulResponse(listOfValuations
                            ,request.right.get.symbol
                            ,request.right.get.function
                            ,StatusCodes.SUCCESS))
}

但我怀疑直接访问 any 不是一个好习惯,例如在

request.right.get.symbol

什么是实现相同行为但以可推荐的方式进行的好方法?

【问题讨论】:

    标签: scala functional-programming monads either


    【解决方案1】:

    在 Scala 2.12 及更高版本中两者都偏右,因此您可以使用 for-comprehension

      def getResponse(handlingResult : Either[FailureReason, List[StockValuation]]
                      ,request        : Either[Error, ValuationRequest]
                     ): ValuationResponse = {
        val result = for {
          result <- handlingResult
          req <- request
        } yield {
          SuccessfulResponse(result, req.symbol, req.function, SUCCESS)
        }
        result match {
          case Right(resp) => resp
          case Left(FailureReason(msg, code)) => FailingResponse(msg, code)
          case Left(Error) => FailingResponse("failed for unknown reasons", SOME_NEW_CODE)
        }
      }
    

    请注意,尽管您不希望最后一个 case 语句匹配,但它应该存在以确保完整性,并且可以创建一个新代码 SOME_NEW_CODE 来指示发生了意外情况。

    【讨论】:

    • 实际上,如果我只有 1 或 2 个案例,编译器甚至不会抱怨。在匹配中,编译器只告诉我该对象是可序列化的......很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2018-12-30
    • 2011-05-28
    相关资源
    最近更新 更多