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.