如何在功能上组合 Scala 的 Either
How to functionally compose Scala's Either
如果我有一个或多个 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
}
让我知道是否还有任何我可以添加的内容以使我的问题更清楚。
可能是这样的:
ether
.right
.flatMap(anotherEither(_).right)
.flatMap(yetAnother(_).right)
.left
.map { err => logError(_.getMessage); err }
如果我有一个或多个 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
}
让我知道是否还有任何我可以添加的内容以使我的问题更清楚。
可能是这样的:
ether
.right
.flatMap(anotherEither(_).right)
.flatMap(yetAnother(_).right)
.left
.map { err => logError(_.getMessage); err }