Option, Either and Error Handling
Scala uses Option
and Either
for safe, expressive error handling without exceptions.
Option
def findUser(id: Int): Option[String] = {
if (id == 1) Some("Alice") else None
}
val result = findUser(2).getOrElse("Unknown")
Either
def divide(a: Int, b: Int): Either[String, Int] = {
if (b == 0) Left("Cannot divide by zero") else Right(a / b)
}
val output = divide(4, 2).fold(err => err, res => res.toString)
Use these to write robust, null-safe code.