Explain the use of 'Either' in error handling in Scala.
Instruction: Describe how the 'Either' type is used for error handling and provide an example.
Updated
Either[E, A] represents one of two alternatives. For error handling, Left(error) conventionally represents an expected failure and Right(value) a successful result. Modern Scala's Either is right-biased: map and flatMap operate on Right and propagate Left.
final case class UserData(id: Int, name: String)
enum LookupError { case InvalidId, NotFound }
def lookup(id: Int, users: Map[Int, UserData])
: Either[LookupError, UserData] = {
if (id <= 0) Left(LookupError.InvalidId)
else users.get(id).toRight(LookupError.NotFound)
}
@main def eitherExample(): Unit = {
val users = Map(101 -> UserData(101, "Ada"))
assert(lookup(101, users).map(_.name) == Right("Ada"))
assert(lookup(0, users) == Left(LookupError.InvalidId))
assert(lookup(102, users) == Left(LookupError.NotFound))
val message = lookup(102, users).fold(
error => s"lookup failed: $error", user => user.name)
assert(message == "lookup failed: NotFound")
}
An error algebra such as LookupError makes handled cases explicit without relying on arbitrary strings. A for-comprehension can chain compatible Either values, stopping at the first Left; it does not accumulate all independent validation errors. Either implementation and examples
Returning Either does not automatically catch exceptions thrown before or inside its callbacks. Decide which failures belong in the domain model and convert exceptions only at an appropriate boundary. This example is a pure in-memory lookup, with no claim about database transactions, network failure handling or authorization.