Adam Fraser Adam Fraser - 10 months ago 37
Scala Question

How do I pull apart Case Classes filled with Options in Scala

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
, if they are indeed wearing pants... with pockets, and if they have any money at all?

Answer Source

A great time for for-comprehensions:

val someCash: Option[Cash] =
   for( pants  <- somePerson.pants;
        pocket <- pants.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] = 

(I'm not totally sure if you can write the last expression using the _ wildcards, as I did).