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
- Either for Errors
- Try, Success, Failure
- Composing Either
- Converting Between Types