简体   繁体   中英

map function in Option in scala

I am a bit confused by the 3rd println in the code below, where the output is None . According to my understanding :

  1. lookupPlayer(3) will give None which is a sub type of Option[Nothing]
  2. Then map on None will be called. But how does the map function of None work ?

Please help me to understand with a simple example.

case class Player(name: String)

def lookupPlayer(id: Int): Option[Player] = {
  if (id == 1) Some(new Player("Sean"))
  else if(id == 2) Some(new Player("Greg"))
  else None
}

def lookupScore(player: Player): Option[Int] = {
  if (player.name == "Sean") Some(1000000) else None
}

println(lookupPlayer(1).map(lookupScore))  // Some(Some(1000000))
println(lookupPlayer(2).map(lookupScore))  // Some(None)
println(lookupPlayer(3).map(lookupScore))  // None

From the docs :

final def map[B](f: (A) ⇒ B): Option[B]

Returns a scala.Some containing the result of applying f to this scala.Option's value if this scala.Option is nonempty. Otherwise return None.

So - simply put, None.map(<any function>) returns None .

A map operation to put in a simple term means to transform something say from x1 to x2. here x1 and x1 can either be of same type as

scala> Some(1).map(x => x * 2)
res10: Option[Int] = Some(2)

or it can be of different type

scala> Some(1).map(x => x.toString)
res11: Option[String] = Some(1)

But when there is nothing to transform the output of a map operation is nothing. so map function on None will always return None.

scala> None.map((x: Int) => 0)
res1: Option[Int] = None

This is the definition of map function in Option class. the isEmpty method returns true if the Option is None and hence a map on None will always return None.

  @inline final def map[B](f: A => B): Option[B] =
    if (isEmpty) None else Some(f(this.get))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM