Functional Programming In Scala (1) — Options

Mallika Kulkarni
Sep 29, 2018 · 4 min read
val someOption : Option[String] = Some("Present Value")val noneOption : Option[String] = None
case class Employee (
id: Int,
name: String,
gender: Option[String],
tenure: Int
)
object EmployeeDB {
private val employees = Map(
1 -> Employee(1, "John Deer", Some("Male"), 5),
2 -> Employee(2, "Jane Doe", None, 3)
)

def findEmployeeById(id: Int) : Option[Employee] = {
employees.get(id)
}
}
val employee = Employee(2, "Jane Doe", None, 3)
println(employee.gender.getOrElse("Not specified"))
val resOpt = EmployeeDB.findEmployeeById(1)
if (resOpt.isDefined)
println(resOpt.get.name) //Prints John Deer
Employee res = EmployeeDB.findEmployeeById(1);
if (res != null) {
System.out.Println(res.name)
}
val employee = Employee(2, "Jane Doe", None, 3)
employee.gender match {
case Some(gender) => println(gender)
case None => println("Not specified")
}
val employee = Employee(2, "Jane Doe", None, 3)
val gender = employee.gender match {
case Some(spec) => spec
case None => "Not specified"
}
println(gender)
EmployeeDB.findEmployeeById(1).foreach(employee => println(employee.name))
val nameOpt = EmployeeDB.findEmployeeById(1).map(_.name) // nameOpt = Some("John Deer")
val genderOpt = EmployeeDB.findEmployeeById(1).map(_.gender)
val gender1 = EmployeeDB.findEmployeeById(1).flatMap(_.gender) //gender is Some("Male")val gender2 = EmployeeDB.findEmployeeById(2).flatMap(_.gender) //gender is None
val numberOpts = List(Some(1), None, Some(2), None)
val numbers = numberOpts.flatten.map(num => num * 2) // List(1, 2)
EmployeeDB.findEmployeeById(1).filter(_.tenure >= 5) //Some(employee) because tenure = 5EmployeeDB.findEmployeeById(2).filter(_.tenure >= 5) //None because tenure = 3
for {
employee <- EmployeeDB.findEmployeeById(1)
gender <- employee.gender
} yield {
println(gender)
} // prints Some("Male")

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade