相关疑难解决方法(0)

在Scala中将选项转换为Either

假设我需要在Scala中转换Option[Int]Either[String, Int].我想这样做:

def foo(ox: Option[Int]): Either[String, Int] =
  ox.fold(Left("No number")) {x => Right(x)}
Run Code Online (Sandbox Code Playgroud)

不幸的是上面的代码没有编译,我需要Either[String, Int]显式添加类型:

ox.fold(Left("No number"): Either[String, Int]) { x => Right(x) }
Run Code Online (Sandbox Code Playgroud)

是否可以在不添加类型的情况下转换OptionEither这种方式?
您如何建议转换OptionEither

scala type-conversion option either

23
推荐指数
2
解决办法
1万
查看次数

标签 统计

either ×1

option ×1

scala ×1

type-conversion ×1