I'm very new to Scala and I'm still trying to get used to the syntax and style, so this is probably a very simple question.
I'm working with a codebase where there are lots of case classes populated with Options like so:
case class Person(
pants: Option[Pants]
)
case class Pants(
pocket: Option[Pocket]
)
case class Pocket(
cash: Option[Cash]
)
case class Cash(
value: String = "zilch"
)
In the example above, how would you go about returning how much money is in a Person
's Pants
Pocket
, if they are indeed wearing pants... with pockets, and if they have any money at all?
A great time for for-comprehensions:
val someCash: Option[Cash] =
for( pants <- somePerson.pants;
pocket <- pants.pocket;
cash <- pocket.cash ) yield cash
Equivalently you can write the following, for which the first code is syntactic sugar (ignoring some subtleties):
val someCash: Option[Cash] =
somePerson.pants.flatMap(_.pocket.flatMap(_.cash))
(I'm not totally sure if you can write the last expression using the _
wildcards, as I did).