Problem
val maybeStreet: Option[String] = ???
val maybeNumber: Option[Int] = ???
val maybeZipCode: Option[Int] = ???
case class Address(street: String, number: Int, zipCode: Int)
val maybeAddress: Option[Address] = maybeStreet.flatMap(street =>
maybeNumber.flatMap(number =>
maybeZipCode.map(zipCode => Address(street, number, zipCode))))
Lösung
val address: Option[Address] = for {
street <- maybeStreet
number <- maybeNumber
zipCode <- maybeZipCode
} yield Address(street, number, zipCode)
Weiterführende Aspekte
val result: List[(Int, String)] = for {
a <- List(1, 2, 3)
b <- List("A", "B", "C")
} yield (a, b)
// Result: List((1, "A"), (1, "B"), "....
---
Autor: Aleksandar Stoimenov
Toilet Paper #157 als Download: For-Comprehensions und Monaden in Scala (PDF)
Lust, das nächste ToiletPaper zu schreiben? Jetzt bei jambit bewerben!