0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Converting Between Types

Option, Either, Try.

Three Error Models

Scala offers three complementary types for absence and failure:

  • Option — presence or absence (no reason).
  • Either — success or a typed error.
  • Try — success or a thrown exception.

Knowing how to convert between them lets you adapt one API to another.

Option to Either

toRight converts an Option to an Either, supplying a Left error for the None case. toLeft does the reverse mapping.

@main def run(): Unit = {
  val some: Option[Int] = Some(5)
  val none: Option[Int] = None
  println(some.toRight("missing"))
  println(none.toRight("missing"))
}

All lessons in this course

  1. Either for Errors
  2. Try, Success, Failure
  3. Composing Either
  4. Converting Between Types
← Back to Scala for Backend Engineering & Functional Programming