Using map and flatMap with Option
In the previous post we looked at the difference between map and flatMap. In this one, we will look at how to use them on the Option container type. Option is an idiomatic way of handling null values in Scala. Let us look at the snippet below,
case class Employee(id : Int, name : String, depId : Int) case class Department(id : Int, name : String) def lookupEmployee(id : Int) = id match { case 1 => Option(Employee(1, "Fred", 1)) case 2 => Option(Employee(2, "Barney", 2)) case _ => None } def lookupDepartment(id : Int) = id match { case 1 => Option(Department(1, "Education")) case _ => None }
There are two functions, one to look up an employee by id and another look up a department id. Now we can look at chaining the two operations, first looking up the employee by Id and then looking up the employee’s department, using both map and flatMap.
If we use map as shown below for an employee and a department that exist, we will get an Option[Option[Department]] of value Some(Some(Department(1, “Education”))).
lookupEmployee(1) map { x => lookupDepartment(x.id) }
However, if we use flatMap as shown below for an employee and a department that exist, we will get an Option[Department] of value Some(Department(1, “Education”)).
lookupEmployee(1) flatMap { x => lookupDepartment(x.id) }
Leave a Reply