How do you implement error handling in functional programming with Scala?
Instruction: Discuss approaches to error handling in Scala, focusing on functional programming paradigms.
Context: This question probes the candidate's ability to handle errors in a functional style in Scala, emphasizing the use of Either, Try, and Option types to represent computations that might fail.
Updated
Choose the result type according to what the caller needs to know:
Option[A]represents presence or absence without an error reason.Either[E, A]represents an explicit error or successful value. In Scala 2.12 and later, including Scala 3, it is right-biased:mapandflatMapoperate onRightand preserveLeft.Try[A]captures nonfatal exceptions asFailure, or a successful value asSuccess. It is useful at an exception-throwing library boundary.
def positiveInt(raw: String): Either[String, Int] =
Option(raw).flatMap(_.toIntOption).toRight("Invalid integer").flatMap { value =>
if (value > 0) Right(value) else Left("Must be positive")
}
@main def functionalErrorsExample(): Unit = {
assert(positiveInt("7").map(_ * 2) == Right(14))
assert(positiveInt("0") == Left("Must be positive"))
assert(positiveInt("bad") == Left("Invalid integer"))
assert(positiveInt(null) == Left("Invalid integer"))
}
This Scala 3 example preserves the reason for failure and sequences dependent validation. It returns the first error; it does not accumulate all independent errors. It also does not trim whitespace or make later arithmetic overflow-safe. Either semantics
These types do not make arbitrary callbacks total or non-throwing. Translate only failures you understand, keep unexpected causes observable, and manage resources separately. Avoid collapsing a service outage into None or returning a fabricated successful value. Try and nonfatal exceptions