Scala Medium · Lesson 1 · On the house

Either

Left/Right, map, flatMap, fold, vs Option. Lesson 1 is free — on the house.

Lessons · Scala Medium · Lesson 1 of 10 · On the house

Either

Left/Right, map, flatMap, fold, vs Option.

Illustration for Scala
Lesson 1 is on the house.

Either[A, B] is a disjoint union: Left(a) or Right(b). By convention Right is the success path and Left carries failure detail (message, error code, validation). Prefer Either when absence alone (None) is not enough — you need to say why.

e.map(f) maps over Right and leaves Left untouched. e.flatMap(f) chains when f returns another Either (avoids Either[A, Either[A, C]]). e.fold(fa, fb) handles both sides into one result type.

e.left.map(f) (via left projection / swap in Scala 2) transforms the failure side. Pattern match when branches differ: e match { case Right(v) => ...; case Left(err) => ... }.

Convert from Option: opt.toRight("missing") → Either[String, A]. The reverse: e.toOption drops the Left detail. Use Either for validation pipelines; use Option when only presence matters.

Misses: treating Left as success, stacking map when you needed flatMap (nested Eithers), or using null/exceptions where a typed Left would document failure.

either

object EitherDemo {
  def parseAge(s: String): Either[String, Int] =
    try {
      val n = s.toInt
      if (n >= 0) Right(n) else Left("negative")
    } catch {
      case _: NumberFormatException => Left("not an int")
    }

  def main(args: Array[String]): Unit = {
    val a = parseAge("36")
    val b = parseAge("x")
    println(a.map(_ + 1))
    println(b.map(_ + 1))
    val label = a.fold(err => s"fail=$err", n => s"age=$n")
    println(label)
    val chained = parseAge("20").flatMap { n =>
      if (n >= 18) Right(n) else Left("underage")
    }
    println(chained)
  }
}
Match this when you type.

Quiz

By convention, which Either side is success?

Quiz

What does Right(36).map(_ + 1) yield?

Quiz

When do you need flatMap on Either?

Quiz

What does e.fold(fa, fb) do?

Check

Match the still for: Either.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.