Creating Either

Again, as in the case of Option, an obvious way to create an instance of Either is to use the constructor of the respective case class:

scala> Right(10)
res1: scala.util.Right[Nothing,Int] = Right(10)

The caveat is that the preceding definition leaves us with an Either whose left side is of the type Nothing. This probably wasn't our intention. Therefore, it is desirable to provide type parameters for both sides:

scala> Left[String, Int]("I'm left")
res2: scala.util.Left[String,Int] = Left(I'm left)

This is arguably a bit cumbersome.

Again, similar to Option, the Either companion object offers a helpful constructor which takes a predicate and two by-name constructors for the right and left sides:

scala> val i = 100
i: Int = 100
scala> val either = Either.cond(i > 10, i, "i is greater then 10")
either: scala.util.Either[String,Int] = Right(100)

If the condition holds, the Right with a given argument is constructed, otherwise a Left is created. Because both sides are defined, the compiler can inference the resulting type of Either properly.

There are two helper methods that are defined on both the Left and Right that help to upcast the previously defined side to full Either:

scala> val right = Right(10)
right: scala.util.Right[Nothing,Int] = Right(10)
scala> right.withLeft[String]
res11: scala.util.Either[String,Int] = Right(10)
scala> Left(new StringBuilder).withRight[BigDecimal]
res12: scala.util.Either[StringBuilder,BigDecimal] = Left()

Here, we upcast Right[Nothing,Int] to Either[String,Int] and do the same with Left, which produces the resulting value of the type Either[StringBuilder,BigDecimal].

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

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