how do I process returned Either

user398384 picture user398384 · Aug 16, 2010 · Viewed 16k times · Source

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 ?

Answer

Rex Kerr picture Rex Kerr · Aug 16, 2010

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