我想在 Scala 中使用 alternative
和 Either[A, B]
。
这是我想到的:
scala> val x: Either[String, Int] = Left("Foo")
x: Either[String,Int] = Left(Foo)
scala> val y: Either[String, Int] = Right(5555)
y: Either[String,Int] = Right(5555)
scala> x.fold(_ => y, _ => x)
res1: Either[String,Int] = Right(5555)
这是仅使用标准库时的惯用方法吗?
我担心的是,当我使用超过 2 个Either
时,我将拥有相当多的 fold
。
最佳答案
也许有一些拉皮条:
implicit class EitherOps[A,B] (x: Either[A,B]) {
def orElse (y: => Either[A,B]) = x.fold(_ => y, _ => x)
}
x orElse y orElse z
请记住,它会丢弃除最后一个之外的所有可能的 Left
(您的示例代码也是如此)。
(更新:按照 Odomontois 在评论中的建议使用名称传递)
关于scala - 与任一选项的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33961701/