0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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

  1. Avoiding null
  2. map and flatMap on Option
  3. getOrElse and fold
  4. Option in for-comprehensions
← Back to Scala for Backend Engineering & Functional Programming