map and flatMap on Option
Compose safely.
Transforming an Option
Often you have an Option and want to transform the value if it is present, leaving None untouched.
The map method does exactly this, without unwrapping by hand.
Using map
map applies a function to the value inside a Some and returns a new Some. On None it does nothing and returns None.
object Main {
def main(args: Array[String]): Unit = {
val n: Option[Int] = Some(10)
val doubled = n.map(x => x * 2)
println(doubled)
}
}All lessons in this course
- Avoiding null
- map and flatMap on Option
- getOrElse and fold
- Option in for-comprehensions