如果是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)
或者你可以用它喜欢getOrElse在Option:
scala> a.fold( l => "Default" , r => r )
res2: String = On
Run Code Online (Sandbox Code Playgroud)
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
| 归档时间: |
|
| 查看次数: |
11686 次 |
| 最近记录: |