【问题标题】:How to functionally compose Scala's Either如何在功能上组合 Scala 的 Either
【发布时间】:2018-01-08 16:41:35
【问题描述】:

如果我有一个或多个 Either 值,我如何以函数方式组合它们,以便在存在左值时记录错误,但在存在右值时继续在函数中。例如

def composeEither(ethr: Either[Error, String]): Either[Error, String] = {
     ethr match { case Left(err) => log.error(err.getMessage) }

     //this obviously will not work but something like map that is right biased         
     ethr map { e => e } //Just for the sake of example - there might be a different either calculated within the map         
}

如果我可以添加任何其他内容以使我的问题更清楚,请告诉我。

【问题讨论】:

  • 你应该使用Try而不是Either
  • 我正在使用一个返回 Either 的第三方库,我想保持代码干净,如果我不需要的话,不要随意转换。
  • 您使用的是 Scala 2.11(不偏不倚)还是 2.12(偏右偏倚)?
  • 不幸的是 2.11

标签: scala functional-programming either


【解决方案1】:

可能是这样的:

  ether
   .right
   .flatMap(anotherEither(_).right)
   .flatMap(yetAnother(_).right)
   .left
   .map { err => logError(_.getMessage); err }

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多