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
.
B
is just a name for the variable type parameter. It only has meaning within its scope. In other words B
in map
and flatMap
definitions do not have to be the same, they are completely different parameters.
The could have written absolutely equivalently:
def flatMap[C](f: A => Option[C]): Option[C] =
map(f) getOrElse None
Now, in this terms, it is easy to see, that map
used here has Option[C]
as the value for its type parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.