The Either Type
An Either holds one of two possible answers, usually a bad one on the left or a good one on the right. It is like a door that opens to either a prize or an explanation.
In this page:
Syntax
def function_name(param: Type): Either[ErrorType, ResultType] =
if (condition) Right(value) else Left(error)
result match {
case Left(error) => expression
case Right(value) => expression
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Assuming
Leftis the success value, when by conventionRightis the correct value andLeftis the error. - Forgetting the types, such as
Either[String, Int], so the compiler infersEither[String, Nothing]. - Calling
.geton anEither, when it has nogetand you should usematch,maporfold.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: