Hey everyone, I’m back with another blog in which we are going to explore Either in Cats Library. For an introduction to Either Monad in Cats and comparison between Either in standard Scala Library and Cats Library, you can have a look at my previous blog i.e Either in Cats vs Either in Scala. Also, if you don’t know what is a Monad you can have a look at this blog.
In this blog, we will be exploring many extension methods that are provided in Cats which can be very helpful. So, let’s dive in!
Either Monad in Cats
Either is a Monad that represents a value of two possible types i.e. ether Right(correct value) or Left(error/failure).
In Cats we can create object of Either type in following ways:
- By using Right.apply and Left.apply

- By importing cats.syntax.either._, which will provide us with many helpful methods and one of those are “Smart Constructors”

For the detailed difference between the two you can visit my previous blog.
Moving forward, let’s discuss different extension methods provided to us after importing the syntax.
Extension Methods
catchOnly
It can be used to catch exception of a specific kind. If we catch the specific exception then it will wrap the exception in Left otherwise the value will be wrapped in Right.
It is good if you are concerned about a specific exception.
The problem with this is that the other exceptions will be propagated.


Similar to this we have caatchNonFatal too, which will only catch non-fatal exceptions.
getOrElse
It is for extracting value from Right or returning a default.


Similar to this we have orElse also.
ensure
It will allow us to check if the right value satisfies a predicate. If not then it will return value of Left type.


recover
As the name suggests it is for recovering from the error. In recover block, we give a partial function and on basis of that, if the error occurs, the value will be recovered. In short, instead of error i.e. a left value it will return a Right value.


Similar to this, we have recoverWith also.
The “map” method works on the right value only. To complement it we have the following:
leftMap
This will do the mapping on left value in Either.


biMap
It will map both the values and for both of them, we can have different mappings.


We also have conversion methods which convert others to Either and also converts Either to others. Let’s look at them as well.
toOption
It will convert an Either to Option. If we have a Right value then it will be wrapped in Some else None.


fromOption
It will take Option value and convert it to Either.


There are many more similar methods such as fromTry, toTry, toList etc.
That’s all for this blog. Here you can find all the code. I hope it was helpful 😀
If you like it, give it a thumbs up. See you in the next blogs.