Reputation: 361
I am a bit confused by the 3rd println
in the code below, where the output is None
. According to my understanding :
lookupPlayer(3)
will give None
which is a sub type of Option[Nothing]
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
Upvotes: 1
Views: 4099
Reputation: 11577
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))
Upvotes: 1
Reputation: 37822
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
.
Upvotes: 5