Reading values from Either

Either is different from Option in the sense that it represents two possible values instead of one. Accordingly, we can't just check if Either contains a value. We have to specify which side we're talking about:

if (either.isRight) println("Got right")
if (either.isLeft) println("Got left")

They are of little use if compared to the Option's approach because Either does not offer a method to extract the value from it. In the case of Either, pattern matching is a way to go:

either match {
case Left(value) => println(s"Got Left value $value")
case Right(value) => println(s"Got Right value $value")
}

The predicate functions are also available with semantics similar to Option, with None represented by Left and Some by Right:

if (either.contains("boo")) println("Is Right and contains 'boo'")
if (either.exists(_ > 10)) println("Is Right and > 10")
if (either.forall(_ > 10)) println("Is Left or > 10")

This special treatment of Right as a default side makes Either right-biased. Another example of this bias is the getOrElse function, which also returns the contents of the Right side or the default value provided as an argument in the case of Left:

scala> val left = Left(new StringBuilder).withRight[BigDecimal]
res14: scala.util.Either[StringBuilder,BigDecimal] = Left()

scala> .getOrElse("Default value for the left side")
res15: String = Default value for the left side

The right bias plays very well for the conversion to Option, with Some representing the right side and None the left side, regardless of the value of Left:

scala> left.toOption
res17: Option[BigDecimal] = None

Similarly, toSeq represents Right as a Seq of one element and Left as an empty Seq:

scala> left.toSeq
res18: Seq[BigDecimal] = List()

In the case of there being a Left that we'd like to be Right or vice versa, there is a swap method whose sole purpose is to changes sides:

scala> left.swap
res19: scala.util.Either[BigDecimal,StringBuilder] = Right()

This can help to apply the right-biased methods if a value that needs to be applied is on the left side.

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

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