Implement a functional error handling strategy in Scala.

Instruction: Provide an example of a functional approach to error handling in Scala, contrasting it with traditional try/catch mechanisms.

Context: Tests the candidate's proficiency in functional programming principles, specifically in implementing a functional approach to error handling in Scala.

Updated

Represent expected failures as values and compose successful steps without discarding their error information. In this Scala 3 example, Either distinguishes invalid input from a result that would overflow Int:

enum InputError {
  case InvalidInteger, DoubledValueOutOfRange
}
def parseInt(raw: String): Either[InputError, Int] =
  Option(raw).flatMap(_.toIntOption).toRight(InputError.InvalidInteger)

def checkedDouble(value: Int): Either[InputError, Int] = {
  val doubled = value.toLong * 2L
  if (doubled < Int.MinValue || doubled > Int.MaxValue)
    Left(InputError.DoubledValueOutOfRange)
  else Right(doubled.toInt)
}
def process(raw: String): Either[InputError, Int] = for {
  value <- parseInt(raw)
  doubled <- checkedDouble(value)
} yield doubled

@main def errorHandlingExample(): Unit = {
  assert(process("21") == Right(42))
  assert(process("not a number") == Left(InputError.InvalidInteger))
  assert(process(null) == Left(InputError.InvalidInteger))
  assert(process("2147483647") == Left(InputError.DoubledValueOutOfRange))
}

Either is right-biased: these map/flatMap operations continue through Right and propagate a Left without running subsequent dependent steps. This is first-error behavior, not accumulation of every independent validation error. Either semantics

The input policy here does not trim whitespace, and values outside the Int parsing range are invalid. Doubling uses a wider intermediate before checking its range, rather than allowing silent Int overflow. At the application boundary, match each error to an appropriate response and keep unexpected failures observable.

Option is suitable when only presence matters. Try captures nonfatal exceptions from exception-throwing code; a narrow try/catch can translate a known library failure into a domain error. Neither approach justifies catching every throwable or returning a success-shaped default. Scala's try/catch is itself an expression and is not inherently incompatible with functional code. Resource cleanup and transaction boundaries remain separate responsibilities. Try behavior

Related Questions