cool breeze cool breeze - 3 months ago 15
Scala Question

How to return a None if all components are also None, otherwise Some

I have a case class like:

case class Part1(id: Int)
case class Part2(id: Int)
case class Part3(id: Int)

The above are all included in the below Parts class:

case class Parts(part1: Option[Part1], part2: Option[Part2], part3: Option[Part3])

Now currently in my code I have:

case (maybePart1, maybePart2, maybePart3) =>
Parts(maybePart1, maybePart2, maybePart3)

But what I really want to do is return None if all of them are None, otherwise return what I am doing above.

How can I do this?


Just add another case statement for the case if they are all None:

case (None, None, None) => None
case (maybePart1, maybePart2, maybePart3) => 
  Some(Parts(maybePart1, maybePart2, maybePart3))