Skip to main content

Option (WIP)

note

Also check out: Option

map

Option.map is used to change value inside Option.

val maybeNumber = Option(1)
// maybeNumber: Option[Int] = Some(value = 1)

maybeNumber.map(n => n * 2)
// res0: Option[Int] = Some(value = 2)
maybeNumber.map(n => n + 10)
// res1: Option[Int] = Some(value = 11)
maybeNumber.map(n => n - 1)
// res2: Option[Int] = Some(value = 0)

val maybeNumber2: Option[Int] = Option.empty[Int]
// maybeNumber2: Option[Int] = None

maybeNumber2.map(n => n * 2)
// res3: Option[Int] = None
maybeNumber2.map(n => n + 10)
// res4: Option[Int] = None
maybeNumber2.map(n => n - 1)
// res5: Option[Int] = None

flatMap

If the return type of the function passed to Option.map is also Option, use Option.flatMap. Otherwise, you will end up having nested Options like Option[Option[A]]

  • Examples of nested Options
// for value.some to create Option[A] = Some(value) and none[A] to create Option[A] = None
import cats.syntax.all._
val maybeNumber = 1.some
// maybeNumber: Option[Int] = Some(value = 1)

maybeNumber.map(n => (n * 2).some)
// res7: Option[Option[Int]] = Some(value = Some(value = 2))
maybeNumber.map(n => (n + 10).some)
// res8: Option[Option[Int]] = Some(value = Some(value = 11))
maybeNumber.map(n => (n - 1).some)
// res9: Option[Option[Int]] = Some(value = Some(value = 0))

val maybeNumber2 = none[Int]
// maybeNumber2: Option[Int] = None

maybeNumber2.map(n => (n * 2).some)
// res10: Option[Option[Int]] = None
maybeNumber2.map(n => (n + 10).some)
// res11: Option[Option[Int]] = None
maybeNumber2.map(n => (n - 1).some)
// res12: Option[Option[Int]] = None
  • With flatMap
// for value.some to create Option[A] = Some(value) and none[A] to create Option[A] = None
import cats.syntax.all._

val maybeNumber = 1.some
// maybeNumber: Option[Int] = Some(value = 1)

maybeNumber.flatMap(n => (n * 2).some)
// res14: Option[Int] = Some(value = 2)
maybeNumber.flatMap(n => (n + 10).some)
// res15: Option[Int] = Some(value = 11)
maybeNumber.flatMap(n => (n - 1).some)
// res16: Option[Int] = Some(value = 0)

val maybeNumber2 = none[Int]
// maybeNumber2: Option[Int] = None

maybeNumber2.flatMap(n => (n * 2).some)
// res17: Option[Int] = None
maybeNumber2.flatMap(n => (n + 10).some)
// res18: Option[Int] = None
maybeNumber2.flatMap(n => (n - 1).some)
// res19: Option[Int] = None