Scala flatMap implementation

In functional programming, the Scala chapter 4 provides the following definitions for map

, getOrElse

and flatMap

for type Option

:

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 it does flatMap

, but I don't understand how call definition works map(f)

in flatMap

. f

has A => Option[B]

as its type in flatMap

, but we seem to be able to call map

which type function is expecting 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

.

+3


source to share


2 answers


When you call flatMap

and pass a function A => Option[B]

, it flatMap

calls map

and passes the same function , but B

in is flatMap

not the same B

as in map

. For example, if you pass some

Int => Option[String]

      



Then for map

, B = Option[String]

and we'll come back Option[Option[String]]

.

So, getOrElse

in flatMap

to get will, you get inner Option[B]

or return None

.

+4


source


B

is just the name of the variable type parameter. It only makes sense within its own sphere. In other words, the definitions B

in map

and flatMap

do not have to be the same, they are completely different parameters.

One could write absolutely equivalently:



def flatMap[C](f: A => Option[C]): Option[C] = 
  map(f) getOrElse None

      

Now, in these terms, it is easy to see what is map

being used here Option[C]

as meaning for its type parameter.

+2


source







All Articles