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

map and getOrElse on Option

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))
}
🔒

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.