问题描述
假设我需要在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!