← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 3 of 7

map and getOrElse on Option

map on an Option changes the value inside if there is one, while getOrElse gives a backup if the box is empty. It is like adding sprinkles if there is an ice cream, or offering a cookie if not.
Syntax
scala
val mapped = option.map(x => expression)
val result = option.getOrElse(default_value)

map and getOrElse on Option

.map(f) on an Option transforms the wrapped value if present, leaving None untouched, without ever needing an explicit if/pattern match for the common case.

.getOrElse(default) extracts the value if present, or falls back to a default if not -- a safe alternative to .get. Chaining .map followed by .getOrElse is a very common idiom for safely processing an optional value.

Note: option.map(f).getOrElse(default) is one of the most common Option idioms -- transform if present, fall back otherwise.

Example: map and getOrElse on Option

markup
object Main extends App {
  val price: Option[Double] = Some(19.99)
  val noPrice: Option[Double] = None

  val discounted = price.map(p => p * 0.9)
  println(discounted.getOrElse(0.0))
  println(noPrice.map(p => p * 0.9).getOrElse(0.0))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using map where the function itself returns an Option, ending up with Option[Option[A]]; use flatMap.
  2. Calling getOrElse with a default of a different type, which widens the result type to Any.
  3. Expecting map on None to run the function, when it does nothing and returns None.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.