Scala Programming Projects
上QQ阅读APP看书,第一时间看更新

Using Either

The Either type is an ADT that represents a value of either a Left type or a Right type. A simplified definition of Either would be the following:

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

When you instantiate a Right type, you need to provide a value of a B type, and when you instantiate a Left type, you need to provide a value of an A type. Therefore, Either[A, B] can either hold a value of type A or a value of type B.

The following code shows an example of such a usage that you can type in a new Scala worksheet:

def divide(x: Double, y: Double): Either[String, Double] =
if (y == 0)
Left(s"$x cannot be divided by zero")
else
Right(x / y)

divide(6, 3)
// res0: Either[String,Double] = Right(2.0)
divide(6, 0)
// res1: Either[String,Double] = Left(6.0 cannot be divided by zero)

The divide function returns either a string or a double:

  • If the function cannot compute a value, it returns an error String wrapped in a Left type
  • If the function can compute a correct value, it returns the Double value wrapped in a Right type

By convention, we use Right to represent the correct or right value, and we use Left to represent an error.