cool breeze
cool breeze

Reputation: 4811

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?

Upvotes: 0

Views: 112

Answers (1)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6182

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))

Upvotes: 6

Related Questions