map and getOrElse on Option
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: