scala - 与任一选项的替代方案

标签 scala

我想在 Scala 中使用 alternativeEither[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/

相关文章:

scala - Scala super 构造函数中的空值?

sql - SparkSQL 错误表未找到

斯卡拉 : How to split words using multiple delimeters

scala - playframework2 jquery 错误 (jquery.min.map)

scala - 使用 zipWithIndex 对列表项进行分组

scala - 将 Scala 集与子类型集相交

scala - 如何在 Scala 中抑制 "match is not exhaustive!"警告

java - Apache Commons解压缩方法?

arrays - 查找字符串中字符之间的长度

Scala - 模式匹配和 For 循环问题