Yai*_*adt 2 scala either scala-option
我想将 an 转换Either[A, B]为选项,这样 if Eitheris Leftit is Some[A],如果 it is Rightit is None。
到目前为止我已经想出了
either.swap.map(Some(_)).getOrElse(None)
Run Code Online (Sandbox Code Playgroud)
这有点拗口。
和
either match {
case Left(value) => Some(value)
case Right(_) => None
}
Run Code Online (Sandbox Code Playgroud)
这很好,但理想情况下我想知道是否有更惯用的方法使用方法而不是显式匹配。
将路易斯的评论转换为我们的答案
either.swap.toOption
Run Code Online (Sandbox Code Playgroud)
例如
val either: Either[String, Int] = Left("Boom")
either.toOption
either.swap.toOption
Run Code Online (Sandbox Code Playgroud)
输出
res0: Option[Int] = None
res1: Option[String] = Some(Boom)
Run Code Online (Sandbox Code Playgroud)
我们注意到either.toOptionreturnsOption[Int]而either.swap.toOptionreturns Option[String]。
很抱歉复制路易斯的评论,但在我看来,它足够有用,可以作为答案发布。