20

如果一个scala函数是

def A(): Either[Exception, ArrayBuffer[Int]] = {
...
}

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

4

3 回答 3

46

我通常更喜欢使用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)

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

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

或者你可以像getOrElse在这样使用它Option

scala> a.fold( l => "Default" , r => r )
res2: String = On
于 2010-08-16T19:18:05.960 回答
16

最简单的方法是模式匹配

val a = A()

a match{
    case Left(exception) => // do something with the exception
    case Right(arrayBuffer) => // do something with the arrayBuffer
}

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

于 2010-08-16T19:08:01.070 回答
4

一种方法是

val a = A();
for (x <- a.left) {
  println("left: " + x)
}
for (x <- a.right) {
  println("right: " + x)
}

实际上只会计算 for 表达式的主体之一。

于 2010-08-16T19:17:42.717 回答