将Either [A,B]转换为Option [A],其中Left变为Some

时间:2019-12-03 14:28:50

标签: scala either scala-option

我想将Either[A, B]转换为选项,这样,如果EitherLeft,则为Some[A],如果为Right,则为是None

到目前为止,我已经提出了

either.swap.map(Some(_)).getOrElse(None)

有点口。

either match { 
  case Left(value) => Some(value)
  case Right(_) => None
}

很好,但是理想情况下,我想知道是否存在使用方法而不是显式匹配的惯用方式。

1 个答案:

答案 0 :(得分:2)

转换路易斯的评论以回答我们有

either.swap.toOption

例如

val either: Either[String, Int] = Left("Boom")
either.toOption
either.swap.toOption 

输出

res0: Option[Int] = None
res1: Option[String] = Some(Boom)

我们注意到either.toOption返回Option[Int],而either.swap.toOption返回Option[String]

用于在Luis的评论中进行复制的道歉,但IMO足以将其发布为答案。