Either for Errors
Left and Right.
Either for Errors is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 1 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.
Why Either?
Either represents a value that can be one of two possibilities. It is the idiomatic way to model computations that may fail with information about the failure.
Leftconventionally holds the error.Rightconventionally holds the success value.
Unlike Option, which only tells you something is missing, Either tells you what went wrong.
The Either Type
Either[A, B] is a sealed trait with two subtypes: Left[A] and Right[B].
The mnemonic: Right is right (correct), Left is the error. This convention lets map and flatMap operate on the success side automatically.
val ok: Either[String, Int] = Right(42)
val err: Either[String, Int] = Left("boom")
println(ok)
println(err)Returning Either from a Function
A function that can fail returns an Either instead of throwing. The caller can then handle both outcomes explicitly.
object Main {
def parseAge(s: String): Either[String, Int] =
s.toIntOption match {
case Some(n) if n >= 0 => Right(n)
case Some(_) => Left("age cannot be negative")
case None => Left("not a number")
}
def main(args: Array[String]): Unit = {
println(parseAge("30"))
println(parseAge("-5"))
println(parseAge("x"))
}
}Pattern Matching on Either
The most direct way to consume an Either is pattern matching. You handle Left and Right separately.
@main def run(): Unit = {
val result: Either[String, Int] = Right(10)
val msg = result match {
case Right(value) => s"Got value: $value"
case Left(error) => s"Failed: $error"
}
println(msg)
}fold: Collapse Both Sides
fold takes two functions: one for Left and one for Right, and produces a single result of a common type.
It is a concise alternative to pattern matching when you want a value back.
@main def run(): Unit = {
val r: Either[String, Int] = Right(7)
val label = r.fold(
err => s"error: $err",
num => s"double is ${num * 2}"
)
println(label)
}map Works on the Right
map transforms the Right value and leaves a Left untouched. This is the right-biased behavior of Scala's Either (since 2.12).
@main def run(): Unit = {
val ok: Either[String, Int] = Right(5)
val no: Either[String, Int] = Left("missing")
println(ok.map(_ + 1))
println(no.map(_ + 1))
}getOrElse and Defaults
getOrElse extracts the Right value or returns a fallback when the Either is a Left.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(99)
val no: Either[String, Int] = Left("oops")
println(ok.getOrElse(0))
println(no.getOrElse(0))
}swap: Flip the Sides
swap exchanges Left and Right. This is handy when you want to operate on the error side using right-biased methods.
@main def run(): Unit = {
val err: Either[String, Int] = Left("bad input")
val swapped = err.swap.map(_.toUpperCase)
println(swapped)
}isLeft and isRight
Quick boolean checks let you branch without full pattern matching.
isRightreturns true for a success.isLeftreturns true for an error.
@main def run(): Unit = {
val r: Either[String, Int] = Right(1)
println(r.isRight)
println(r.isLeft)
}toOption: Discard the Error
When you no longer care why something failed, toOption converts an Either into an Option: Right(x) becomes Some(x) and Left(_) becomes None.
@main def run(): Unit = {
val ok: Either[String, Int] = Right(3)
val no: Either[String, Int] = Left("err")
println(ok.toOption)
println(no.toOption)
}A Validation Example
Putting it together: validate a username, returning a typed error on failure.
object Main {
def validate(name: String): Either[String, String] =
if (name.isEmpty) Left("empty name")
else if (name.length > 10) Left("name too long")
else Right(name)
def main(args: Array[String]): Unit = {
println(validate("alice"))
println(validate(""))
println(validate("verylongusername"))
}
}Quick Check
Test your understanding of Either conventions.
Recap
You learned to model errors with Either:
Right= success,Left= error (right-biased).- Consume with pattern matching or
fold. - Transform the success with
map; provide defaults withgetOrElse. - Flip sides with
swap; convert withtoOption.
Next, you will handle exceptions with Try.
Frequently asked questions
Is the “Either for Errors” lesson free?
Yes — the full text of “Either for Errors” 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 “Either for Errors”?
Left and Right. 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 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Either for Errors” 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