softshipper
softshipper

Reputation: 34061

Understanding getOrElse usage and dotless function composition

I have following codes:

sealed trait Option[+A] {

  def map[B](f: A => B): Option[B] = this match {
    case None => None
    case Some(a) => Some(f(a))
  }

  def getOrElse[B>:A](default: => B): B = this match {
    case None => default
    case Some(a) => a
  }

  def flatMap[B](f: A => Option[B]): Option[B] =
    map(f) getOrElse None
}
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]

The body of the flatMap function, how does it works? It is not a function composition. What kind of function call it is?

How to use getOrElse method?

Upvotes: 0

Views: 338

Answers (1)

Alon Segal
Alon Segal

Reputation: 848

map(f) getOrElse None is equivalent to the expression map(f).getOrElse(None) which simply call the map() function with the input f and then call the getOrElse on the result, which returns the value x for Some(x) or None in case map returns with None.

Some(5).getOrElse(0) will return 5 None.getOrElse(0) will return 0

Upvotes: 4

Related Questions