Converting Between Types
Option, Either, Try.
Converting Between Types is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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"))
}Either to Option
toOption drops the error: Right(x) becomes Some(x) and Left(_) becomes None. Use this when the reason for failure no longer matters.
@main def run(): Unit = {
val r: Either[String, Int] = Right(42)
val l: Either[String, Int] = Left("err")
println(r.toOption)
println(l.toOption)
}Try to Option
Try.toOption turns a Success into Some and a Failure into None, swallowing the exception.
import scala.util.Try
@main def run(): Unit = {
println(Try("7".toInt).toOption)
println(Try("x".toInt).toOption)
}Try to Either
Try.toEither produces an Either[Throwable, T]: Success becomes Right, Failure becomes Left(throwable). This preserves the exception as a typed left.
import scala.util.Try
@main def run(): Unit = {
val ok = Try("7".toInt).toEither
val no = Try("x".toInt).toEither
println(ok)
println(no.left.map(_.getMessage))
}Either to Try
There is no direct built-in for Either to Try with a plain error, but you can build one: wrap a Right in Success and a Left in a Failure carrying an exception.
import scala.util.{Try, Success, Failure}
object Main {
def toTry(e: Either[String, Int]): Try[Int] = e match {
case Right(v) => Success(v)
case Left(m) => Failure(new RuntimeException(m))
}
def main(args: Array[String]): Unit = {
println(toTry(Right(1)))
println(toTry(Left("bad")))
}
}Option to Try
Convert an Option to a Try by choosing an exception for the empty case. This is useful when an API expects a Try.
import scala.util.{Try, Success, Failure}
object Main {
def toTry[A](o: Option[A]): Try[A] = o match {
case Some(v) => Success(v)
case None => Failure(new NoSuchElementException("empty"))
}
def main(args: Array[String]): Unit = {
println(toTry(Some(9)))
println(toTry(None))
}
}Normalizing a Pipeline
Mixing types causes friction. A common approach is to convert everything to Either with a uniform error type early, then compose freely.
import scala.util.Try
object Main {
def parse(s: String): Either[String, Int] =
Try(s.toInt).toEither.left.map(_ => s"invalid: $s")
def lookup(n: Int): Either[String, String] =
Map(1 -> "one", 2 -> "two").get(n).toRight(s"no entry for $n")
def main(args: Array[String]): Unit = {
val result = for {
n <- parse("2")
w <- lookup(n)
} yield w
println(result)
}
}getOrElse Across Types
All three types support getOrElse to extract a value or supply a default. This is often the final step that exits the error-handling world.
import scala.util.Try
@main def run(): Unit = {
val a = Some(1).getOrElse(0)
val b = (Right(2): Either[String, Int]).getOrElse(0)
val c = Try("x".toInt).getOrElse(0)
println(s"$a $b $c")
}Choosing the Right Type
Guidelines:
- Use Option when absence needs no explanation.
- Use Either when you want a domain-specific error value.
- Use Try at boundaries with exception-throwing Java/library code.
End-to-End Example
Reading exception-throwing code with Try, converting to Either for domain errors, and finally to Option for a caller that only cares about presence.
import scala.util.Try
object Main {
def safeDiv(a: Int, b: Int): Option[Int] =
Try(a / b).toEither.left.map(_ => "math error").toOption
def main(args: Array[String]): Unit = {
println(safeDiv(10, 2))
println(safeDiv(10, 0))
}
}Quick Check
Test your conversion knowledge.
Recap
You learned to convert between Option, Either, and Try:
Option.toRight→ Either;Either.toOption→ Option.Try.toOptionandTry.toEitherbridge exceptions to values.- Normalize a pipeline to one error type early.
- Pick the type that matches how much error detail you need.
Frequently asked questions
Is the “Converting Between Types” lesson free?
Yes — the full text of “Converting Between Types” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Converting Between Types”?
Option, Either, Try. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Converting Between Types” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Either for Errors
- Try, Success, Failure
- Composing Either
- Converting Between Types