The Either Type
In this page:
The Either Type
Either[L, R] represents one of two possible outcomes: a Left(value) (conventionally an error) or a Right(value) (conventionally a success). Unlike Try, which is specifically for exceptions, Either lets you use any type you want for the error case, such as a descriptive error message or custom error type. Pattern matching, or the modern .map/.flatMap methods (which operate on the Right side by convention), are the standard ways to work with it.
Note: By convention, Right represents success and Left represents failure -- a helpful mnemonic is that Right also means "correct".
Example: The Either Type
object Main extends App {
def divide(a: Int, b: Int): Either[String, Int] = {
if (b == 0) Left("Cannot divide by zero")
else Right(a / b)
}
val result1 = divide(10, 2)
val result2 = divide(10, 0)
println(result1)
println(result2)
result2 match {
case Right(value) => println(s"Result: $value")
case Left(error) => println(s"Error: $error")
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: