I have 2 options, and I need to take average of the values they hold.
It is possible that one or both may be missing. If one of the value is missing, I would just take other one as the average. But if both are missing, I would resort to some default value.
How can this be done in a clean way?
I can check absence of value using isEmpty, but then won't that would be same as null check?
I guess this is self-explanatory:
... but if not, the basic idea is that you construct a tuple of options, and then pattern match on the tuple.
This has a benefit of explicitly capturing all the four potential cases + having support from the complier - since
Option
is a sealed trait, compiler can check and ensure that all the potential branches of pattern match are covered.