Use of Either in Scala
Use of Either in Scala
In this article, 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.
Join the DZone community and get the full member experience.Join For Free
In this article, 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.
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:
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.
It will print 1. Yes, it is right biased as the map works on Either.right. What if i want to call map on left?
It will print java.lang.NumberFormatException: For input string: "abc".
Using Match case with Either
It will print Right value: 1
Extract value from Either
Let's say we want to extract left value from Either.
will print LeftProjection(Left(java.lang.NumberFormatException: For input string: "abc"))
will print LeftProjection(Right(1))
will print java.lang.NumberFormatException: For input string: "abc".
will print: Exception in thread "main" java.util.NoSuchElementException: Either.left.get on Right
Oops. It had the right value.
We can use getOrElse or fold for default value.
will print Found int: '1'
will print Found an exception: 'java.lang.NumberFormatException: For input string: "abc"'
Check value is Left or Right
Working with Lists using Either
Will give List(Right(R1), Left(0), Right(R2), Left(200), Right(R3), Left(2000), Right(R4)).
Let's understand how. As we know Either is right bias so list.map(x => x.map(_.toUpperCase)), x will only have Right Values which will be converted to uppercase then as we have return type as List[Either[Int, String]] for list.map(_.map(_.toUpperCase)). y will have left and right values. All the left values will be multiplied by 20.
y.toRight(x) checks if value is empty it return Left(x) else Right(y).
y.toLeft(x) checks if value is empty it return Right(x) else Left(y).
There could be a situation where one function is called then another and then another is a chain and the exceptions are thrown freely. How do we track which function actually caused the exception?
will print Exception in fetchElement.
If call callFunctions("0") will print Exception in reciprocal
Thanks for reading!
Published at DZone with permission of Jyoti Sachdeva . See the original article here.
Opinions expressed by DZone contributors are their own.