September 2018
Intermediate to advanced
398 pages
9h 43m
English
Using the same db: Map[String, Int] phrase, containing the ages of different people, the following code is a naive implementation of a function that returns the average age of two people:
def averageAgeA(name1: String, name2: String, db: Map[String, Int]): Option[Double] = { val optOptAvg: Option[Option[Double]] = db.get(name1).map(age1 => db.get(name2).map(age2 => (age1 + age2).toDouble / 2)) optOptAvg.flatten}val db = Map("John" -> 25, "Rob" -> 40)averageAge("John", "Rob", db)// res6: Option[Double] = Some(32.5)averageAge("John", "Michael", db)// res7: Option[Double] = None
The function returns Option[Double]. If name1 or name2 cannot be found in the db map, averageAge returns None. If both names ...
Read now
Unlock full access