替代Either

时间:2015-11-27 16:43:57

标签: 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 fold以上时,我会有相当多的Either

2 个答案:

答案 0 :(得分:2)

也许有一些拉皮条:

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在评论中建议的传递名称)

答案 1 :(得分:1)

也许是这样的,它需要任意数量的Either[] args。仅当所有参数符合相同的类型配置文件时,才会保留类型信息。

def firstRight[A,B](args:Either[A,B]*):Either[A,B] = args match {
  case Right(x)     +: _    => Right(x)
  case Seq(Left(x))         => Left(x)
  case _            +: tail => firstRight(tail: _*)
}