In this blog, we are going to see the use of Either in scala.

We use Options in scala but why do we want to go for Either?

Either is a better approach in the respect that if something fails we can track down the reason, which in Option None case is not possible.

We simply pass None but what is the reason we got None instead of Some. We will see how to tackle this scenario using Either.

Either[Left, Right]

None is similar to Left which signifies Failure and Some is similar to Right which signifies Success.

Let’s see with help of an example:

def returnEither(value: String): Either[NumberFormatException, Int] =
{
try {
Right(value.toInt)
} catch {
case ex: NumberFormatException => Left(ex)
}
}
returnEither("abc").map(x => println(x))

It will not print anything, Either is right biased and returnEither(“abc”) gives Left(java.lang.NumberFormatException: For input string: “abc”)

Now let’s call it on Right value.

returnEither("1").map(x => println(x))

It will print 1. Yes, it is right biased as the map works on Either.right. What if I want to call the map on left?

returnEither("abc").left.map(x => println(x))

It will print** java.lang.NumberFormatException: For input string: “abc”.**

Using Match case with Either

returnEither("1") match
{
case Right(value) => println(s"Right value: $value")
case Left(ex: NumberFormatException) => println(ex)
}

It will print Right value: 1

Extract value from Either

Let’s say we want to extract left value from Either.

println(returnEither("abc").left)

will print LeftProjection(Left(java.lang.NumberFormatException: For input string: “abc”))

println(returnEither("1").left)

will print LeftProjection(Right(1)).

println(returnEither("abc").left.get)

will give java.lang.NumberFormatException: For input string: “abc”.

println(returnEither("1").left.get)

will give: Exception in thread “main” java.util.NoSuchElementException: Either.left.get on Right

Oops. It had right value.

We can use getOrElse or fold for default value.

#scala ##use of either ##use of either in scala #either #scala

Use of Either in Scala
1.70 GEEK