A survival guide to the Either monad in Scala

110 阅读1分钟

A survival guide to the Either monad in Scala

Go to the profile of Luca Florio
Luca FlorioBlockedUnblockFollowFollowing

I started to work with Scala few months ago. One of the concepts that I had the most difficulties to understand is the Either monad. So, I decided to play around with it and better understand its power.

In this story I share what I’ve learned, hoping to help coders approaching this beautiful language.

Photo by Jon Tyson on Unsplash

The Either monad

Either is one of the most useful monads in Scala. If you are wondering what a monad is, well… I cannot go into the details here, maybe in a future story!

Imagine Either like a box containing a computation. You work inside this box, until you decide to get the result out of it.

In this specific case, our Either box can have two “forms”. It can be (either) a Left or a Right, depending on the result of the computation inside it.

I can hear you asking: “OK, and what is it useful for?”

The usual answer is: error handling.

We can put a computation in the Either, and make it a Left in case of errors, or a Right containing a result in case of success. The use of Left for errors, and Right for success is a convention. Let’s understand this with some code!