在 Scala 中将 Option 转换为 Either [英] Convert Option to Either in Scala
问题描述
假设我需要在 Scala 中将 Option[Int]
转换为 Either[String, Int]
.我想这样做:
Suppose I need to convert Option[Int]
to Either[String, Int]
in Scala. I'd like to do it like this:
def foo(ox: Option[Int]): Either[String, Int] =
ox.fold(Left("No number")) {x => Right(x)}
不幸的是,上面的代码无法编译,我需要明确添加类型 Either[String, Int]
:
Unfortunately the code above doesn't compile and I need to add type Either[String, Int]
explicitly:
ox.fold(Left("No number"): Either[String, Int]) { x => Right(x) }
是否可以在不添加类型的情况下以这种方式将 Option
转换为 Either
?
您如何建议将 Option
转换为 Either
?
Is it possible to convert Option
to Either
this way without adding the type ?
How would you suggest convert Option
to Either
?
推荐答案
不,如果你这样做,你不能省略类型.
No, if you do it this way, you can't leave out the type.
Left("No number")
的类型被推断为Either[String, Nothing]
.仅从 Left("No number")
编译器无法知道您希望 Either
的第二种类型为 Int
,并且类型推断并没有走得太远以至于编译器会查看整个方法并决定它应该是 Either[String, Int]
.
The type of Left("No number")
is inferred to be Either[String, Nothing]
. From just Left("No number")
the compiler can't know that you want the second type of the Either
to be Int
, and type inference doesn't go so far that the compiler will look at the whole method and decide it should be Either[String, Int]
.
您可以通过多种不同的方式做到这一点.例如模式匹配:
You could do this in a number of different ways. For example with pattern matching:
def foo(ox: Option[Int]): Either[String, Int] = ox match {
case Some(x) => Right(x)
case None => Left("No number")
}
或者使用 if
表达式:
def foo(ox: Option[Int]): Either[String, Int] =
if (ox.isDefined) Right(ox.get) else Left("No number")
或者用 Either.cond
:
def foo(ox: Option[Int]): Either[String, Int] =
Either.cond(ox.isDefined, ox.get, "No number")
这篇关于在 Scala 中将 Option 转换为 Either的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!