September 2018
Intermediate to advanced
398 pages
9h 43m
English
Since Either is an ADT, we can use pattern matching to decide what to do when we get a Left or Right type.
The following is a modified version of the personDescription function that we showed earlier in the Using Option section:
def getPersonAge(name: String, db: Map[String, Int]): Either[String, Int] = db.get(name).toRight(s"$name is not present in db")def personDescription(name: String, db: Map[String, Int]): String = getPersonAge(name, db) match { case Right(age) => s"$name is $age years old" case Left(error) => error }val db = Map("John" -> 25, "Rob" -> 40)personDescription("John", db)// res4: String = John is 25 years oldpersonDescription("Michael", db)// res5: String = Michael is not present in db
The first getPersonAge ...
Read now
Unlock full access