The Problem with null
In many languages, a method returns
null if it can't find a value. This leads to the infamous NullPointerException. In Scala, we use Option to represent a value that might or might not be there.scala
Working with Option
Wait! You don't "check" an Option with an
if statement. Instead, you use Pattern Matching or Functional Methods.scala
Either (Success or Error)
While
Option represents "Value or Nothing," Either represents "Result A or Result B." By convention, Right is used for success and Left for errors (because "Right" is "correct").scala
Why use them?
- Safety: You are forced to handle the "None" or "Error" case at compile-time.
- Explicit: The function signature tells you exactly what could go wrong.
- No Exceptions: Using
Eitheris much faster and cleaner than throwing and catching exceptions for "expected" errors.
Summary
| Term | Description |
|---|---|
| Option | Represents Some(value) or None |
| Either | Represents Right(success) or Left(error) |
| getOrElse | Provide a default value if missing |
| map | Run logic only if a value exists |
| Best For | Database lookups, API calls, and validation |
| Logic | "Make the possibility of failure explicit in the type" |
| Safety | Eliminates NullPointerExceptions |
| Modern | The standard way to handle optionality in modern functional languages |
| Standard | None is an object; Some is a case class |
| Identity | Options and Eithers are "Monads" (they can be chained!) |