how do I process returned Either

岁酱吖の 提交于 2019-12-04 17:04:02

问题


if a scala function is

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

what should be the right way to process the returned result? val a = A() and ?


回答1:


I generally prefer using fold. You can use it like map:

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)

Or you can use it like a pattern match:

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

Or you can use it like getOrElse in Option:

scala> a.fold( l => "Default" , r => r )
res2: String = On



回答2:


The easiest way is with pattern matching

val a = A()

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

Alternatively, there a variety of fairly straightforward methods on Either, which can be used for the job. Here's the scaladoc http://www.scala-lang.org/api/current/index.html#scala.Either




回答3:


One way is

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

Only one of the bodies of the for expressions will actually be evaluated.



来源:https://stackoverflow.com/questions/3496304/how-do-i-process-returned-either

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!