Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Either map Right or return Left

Tags:

scala

either

Is it possible to handle Either in similar way to Option? In Option, I have a getOrElse function, in Either I want to return Left or process Right. I'm looking for the fastest way of doing this without any boilerplate like:

val myEither:Either[String, Object] = Right(new Object())
myEither match {
    case Left(leftValue) => value
    case Right(righValue) => 
        "Success"
}
like image 966
Michał Jurczuk Avatar asked Dec 31 '15 10:12

Michał Jurczuk


1 Answers

In Scala 2.12,

Either is right-biased, which means that Right is assumed to be the default case to operate on. If it is Left, operations like map, flatMap, ... return the Left value unchanged

so you can do

myEither.map(_ => "Success").merge

if you find it more readable than fold.

like image 125
Alexey Romanov Avatar answered Oct 11 '22 02:10

Alexey Romanov