如果一个scala函数是
def A(): Either[Exception, ArrayBuffer[Int]] = {
...
}
处理返回结果的正确方法应该是什么?
val a = A()
和 ?
我通常更喜欢使用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
最简单的方法是模式匹配
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
一种方法是
val a = A();
for (x <- a.left) {
println("left: " + x)
}
for (x <- a.right) {
println("right: " + x)
}
实际上只会计算 for 表达式的主体之一。