Reputation: 1654
In the book "Functional programming in Scala", Chapter 4 page 55 :
We have the code below :
case class Employee(name: String, department: String)
def lookupByName(name: String): Option[Employee] = ???
// Use of "map"
lookupByName("Joe").map(_.departement)
// Use of "flatMap"
lookupByName("Joe").flatMap(_.manager)
But for me response 1 is false. The function is not returning the department (= a string) but an Some(department) (= an Option).
Am i right or wrong ?
Problem 1 : But for me both responses are false because "manager" is not part of Employee's type so the program is not even compiling.
Problem 2 : Event if i add "manager: String" as part of the Employee type i can't even write lookupByName("Joe").flatMap(_.manager) in Intellij cause i get a "Type mismatch". I must write lookupByName("Joe").flatMap(x => Some(x.manager))
Problem 3 : When i write the function as lookupByName("Joe").flatMap(x => Some(x.manager)) to make my program compile then map and flatMap here have exactly the same results
What am i not understanding here ? What am i doing wrong ?
The resulting here is that i don't get the difference between map and flatMap from those exemples.
Upvotes: 3
Views: 239
Reputation: 39536
Map
You are absolutely right. The return type of lookupByName("Joe").map(_.department)
is Option[String]
(not String
). So, indeed the first case returns Some(<department>)
.
FlatMap
You are right as well. It seems that the authors forgot to declare a third field in the Employee
class. The correct class declaration should be:
case class Employee(name: String, department: String, manager: Option[Employee])
Upvotes: 1