Either

Either represents the possibility of a function having one of two alternative results which can't be represented by a single type.

For example, let's imagine that we have a new simulation system that replaced an old one. The new system is very popular, and so is constantly under load and thus not always available. The old one is kept as a fallback for this reason. Unfortunately, the results of the simulation have very different formats for both systems. Hence, it makes sense to represent them as Either:

type OldFormat
type NewFormat

def runSimulation(): Either[OldFormat, NewFormat]

If this example gives you the feeling that types of alternatives must be related, then you are getting the wrong feeling. Usually, the types of the results would be completely unrelated. To illustrate this, let's consider another example.

As we're fishing, there is the possibility of us catching very different kinds of fish. Yet another possibility is to pull something completely different—an old boot that was lost by a tourist two years ago, or potential evidence that had been concealed by a criminal:

def catchFish(): Either[Boot, Fish]

Traditionally, the right side is preferred to represent the more desirable, right outcome, the left side is less desirable. 

The simplified definition of Either looks like this in the Scala library:

sealed abstract class Either[+A, +B]
final case class Left[+A, +B](value: A) extends Either[A, B]
final case class Right[+A, +B](value: B) extends Either[A, B]

It takes two type parameters for the left and right sides, and there are two case classes representing these sides. Let's dive a bit deeper using the same approach that we did with Option â€“ create an effect, read from the effect, and abstract over it. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.26.138