In Functional Programming in Scala chapter 4 we are provided the following definitions for map, getOrElse and flatMap for the Option type:
def map[B](f: A => B): Option[B] = this match {
case Some(x) => Some(f(x))
case _ => None
}
def getOrElse[B>:A](default: => B): B = this match {
case Some(x) => x
case _ => default
}
def flatMap[B](f: A => Option[B]): Option[B] =
map(f) getOrElse None
I get what flatMap is doing, but I don't get how the call map(f) in flatMap's definition works. f has A => Option[B] as its type in flatMap, yet we seem to be able to call map, which expects a function of type A => B, with f. The call getOrElse None is obviously the key, but I don't understand how it allows us to call map(f) in flatMap.
When you call flatMap and pass the function A => Option[B], flatMap calls map and passes the same function, but the B in flatMap is not same B as in map. For example, if you pass some
Int => Option[String]
Then for map, B = Option[String] and will return Option[Option[String]].
Thus the getOrElse in flatMap to get the will either retrieve the inner Option[B] or return None.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With