我如何处理返回的任何一个

use*_*384 18 scala either

如果是scala函数

def A(): Either[Exception, ArrayBuffer[Int]] = {
...
}
Run Code Online (Sandbox Code Playgroud)

什么应该是处理返回结果的正确方法? val a = A() 和?

Rex*_*err 38

我通常喜欢使用fold.您可以像地图一样使用它:

scala> def a: Either[Exception,String] = Right("On")

a.fold(l => Left(l), r => Right(r.length))
res0: Product with Either[Exception,Int] = Right(2)
Run Code Online (Sandbox Code Playgroud)

或者您可以像模式匹配一​​样使用它:

scala> a.fold( l => {
     |   println("This was bad")
     | }, r => {
     |   println("Hurray! " + r)
     | })
Hurray! On
Run Code Online (Sandbox Code Playgroud)

或者你可以用它喜欢getOrElseOption:

scala> a.fold( l => "Default" , r => r )
res2: String = On
Run Code Online (Sandbox Code Playgroud)

  • 我应该提一下,如果你_only_想用它来映射右侧,`a.right.map(_.length)`打字更少,做你想要的.通常,`.right`和`.left`方法使`Either`工作很像选项,除了保留`None`而不是像'Option`那样的另一种情况,它保留了`Either的另一面. `是.同样,`a.right.getOrElse`比`fold`简单.我喜欢"折叠"的是你可以一次完成所有这些事情并将它们结合起来. (3认同)

Dav*_*ith 16

最简单的方法是使用模式匹配

val a = A()

a match{
    case Left(exception) => // do something with the exception
    case Right(arrayBuffer) => // do something with the arrayBuffer
}
Run Code Online (Sandbox Code Playgroud)

或者,在Either上有各种相当简单的方法,可以用于工作.这是scaladoc http://www.scala-lang.org/api/current/index.html#scala.Either