Last active
June 4, 2021 15:51
-
-
Save rtyley/3eaaa1d0b51193b9d9c8b2323d056769 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class Meal( | |
starter: Option[String], | |
main: String, | |
drinks: Seq[String], | |
tip: Option[Int] | |
) | |
val meals = Seq( | |
Meal( | |
starter = Some("Zucchini Fritters"), | |
main = "Ravioli", | |
drinks = Seq("Mojito", "Wine"), | |
tip = Some(5) | |
), | |
Meal( | |
starter = Some("Papa Qashqai"), | |
main = "Salad", | |
drinks = Seq("Water", "Coffee"), | |
tip = None | |
) | |
) | |
def describeStarterAndTipCombo(meal: Meal): Option[String] = for { | |
starter <- meal.starter // this is an Option[_], so all the other generators must be Option[_] too | |
tip <- meal.tip | |
} yield s"The $starter came so quick, our tip was $tip" | |
describeStarterAndTipCombo(meals.head) | |
def allTheDrinksFrom(meals: Seq[Meal]): Seq[String] = for { | |
meal <- meals | |
drink <- meal.drinks // this is a Seq[_] too, so everything's ok! | |
} yield drink | |
allTheDrinksFrom(meals) | |
def allTipsFrom(meals: Seq[Meal]): Seq[Int] = for { | |
meal <- meals | |
tip <- meal.tip // this works, because Seq[_] has a .flatMap that accepts IterableOnce[_], which Option[_] is | |
} yield tip | |
allTipsFrom(meals) | |
def describeAllStarterAndDrinksCombo(meal: Meal) = for { | |
starter <- meal.starter // this is an Option[_], so the other generators must be Option[_] too | |
drink <- meal.drinks // we'll get a compile error here | |
} yield s"$starter with $drink" | |
describeAllStarterAndDrinksCombo(meals(0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment