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.
In this page:
Syntax
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
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))
}
Login to try C/C++/Java/PHP code in the editor
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
- Using
mapwhere the function itself returns anOption, ending up withOption[Option[A]]; useflatMap. - Calling
getOrElsewith a default of a different type, which widens the result type toAny. - Expecting
maponNoneto run the function, when it does nothing and returnsNone.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: