getOrElse and fold
Extract values.
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))
}
}All lessons in this course
- Avoiding null
- map and flatMap on Option
- getOrElse and fold
- Option in for-comprehensions