0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

getOrElse and fold

Extract values.

getOrElse and fold is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 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.

Getting a Value Out

Eventually you need to extract a plain value from an Option, supplying something sensible when it is None.

Scala provides safe extractors like getOrElse and fold for this.

Using getOrElse

getOrElse returns the value inside a Some, or a default you provide when it is None.

It always gives you a plain value, never an Option.

object Main {
  def main(args: Array[String]): Unit = {
    val a: Option[Int] = Some(5)
    val b: Option[Int] = None
    println(a.getOrElse(0))
    println(b.getOrElse(0))
  }
}

Default Is Lazy

The default in getOrElse is only evaluated when the Option is None. So an expensive default costs nothing when a value is present.

object Main {
  def expensiveDefault(): Int = { println("computing default"); 99 }
  def main(args: Array[String]): Unit = {
    val present: Option[Int] = Some(7)
    println(present.getOrElse(expensiveDefault()))
  }
}

Avoid get

Option has a get method, but it throws an exception on None. This defeats the purpose of using Option.

Prefer getOrElse, fold, or pattern matching instead.

orElse for Fallback Options

orElse is different: it returns the first Option if it is a Some, otherwise it returns a fallback Option.

Use it to try alternatives that themselves may be empty.

object Main {
  def main(args: Array[String]): Unit = {
    val primary: Option[Int] = None
    val backup: Option[Int] = Some(42)
    println(primary.orElse(backup))
  }
}

Introducing fold

fold handles both cases in one call. You give a default for None first, then a function for the Some value.

It returns a single result, transforming the value when present.

object Main {
  def main(args: Array[String]): Unit = {
    val n: Option[Int] = Some(10)
    val result = n.fold(0)(x => x * 2)
    println(result)
  }
}

fold on None

When the Option is None, fold returns the default you gave first, ignoring the transform function.

object Main {
  def main(args: Array[String]): Unit = {
    val empty: Option[Int] = None
    val result = empty.fold(-1)(x => x * 2)
    println(result)
  }
}

fold to a Different Type

Both branches of fold must return the same type, but that type can differ from the Option's value type.

Here we turn an Option[Int] into a String.

object Main {
  def describe(o: Option[Int]): String =
    o.fold("missing")(x => s"value $x")
  def main(args: Array[String]): Unit = {
    println(describe(Some(8)))
    println(describe(None))
  }
}

Choosing Between Them

Quick guide:

  • getOrElse: supply a default value of the same type
  • orElse: supply a fallback Option
  • fold: transform the value and supply a default in one step
  • pattern matching: when each case needs more logic

Combining With map

A common idiom is to map first to transform, then getOrElse to land on a plain value.

object Main {
  def main(args: Array[String]): Unit = {
    val name: Option[String] = Some("ada")
    val display = name.map(_.toUpperCase).getOrElse("ANON")
    println(display)
  }
}

Putting It Together

Look up a config value, provide a fallback Option, then land on a default with getOrElse.

object Main {
  val env = Map("timeout" -> "30")
  def main(args: Array[String]): Unit = {
    val timeout = env.get("timeout")
      .flatMap(_.toIntOption)
      .getOrElse(60)
    println(timeout)
    val retries = env.get("retries").fold(3)(_.toInt)
    println(retries)
  }
}

Quick Check

Test your understanding of extracting Option values.

Recap

You learned to extract Option values safely:

  • getOrElse(default) returns the value or a default (lazily evaluated)
  • orElse(fallback) returns the first Some or a fallback Option
  • fold(default)(f) transforms a Some and defaults a None in one step
  • Avoid get, which throws on None

Frequently asked questions

Is the “getOrElse and fold” lesson free?

Yes — the full text of “getOrElse and fold” 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 “getOrElse and fold”?

Extract values. 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 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “getOrElse and fold” 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

  1. Avoiding null
  2. map and flatMap on Option
  3. getOrElse and fold
  4. Option in for-comprehensions
← Back to Scala for Backend Engineering & Functional Programming