Fpinscala book: Error Handling Using Option Type
In Functional Programming in Scala, Chapter 4, page 55:
We have the following code:
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)
For the "Map" example note, the parties say we have two cases:
- Joe dept if Joe is an employee
- Not if Joe is not an employee
But for me, answer 1 is not correct. The function does not return the department (= string), but Some (department) (= a Option).
Am I right or wrong?
For the "flatMap" example note, the parties say we have two cases:
- Some (manager) if Joe has a manager
- Not if Joe is not an employee or has no manager
Problem 1: But for me both answers are false because the "manager" is not part of the Employee type, so the program doesn't even compile.
Task 2: Eventually, if I add "manager: String" as part of the Employee type, I can't even write lookupByName ("Joe"). flatMap (_. manager) in Intellij is causing me to get "type mismatch", I have to 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 have exactly the same results
What am I missing here? What am I doing wrong?
The result is that I am not getting the difference between map and flatMap from these examples.
source to share
Map
You are absolutely right. The return type lookupByName("Joe").map(_.department)
is Option[String]
(not String
). So indeed the first case returns Some(<department>)
.
FlatMap
You're right. It seems that the authors forgot to declare the third field in the class Employee
. A correct class declaration should be:
case class Employee(name: String, department: String, manager: Option[Employee])
source to share