Search code examples
scalascala-option

Handling two Options in Scala


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?


Solution

  • I guess this is self-explanatory:

    val option1 = Some(12.0)
    val option2 = None
    val default = 0.0
    
    val average = (option1, option2) match {
       case (Some(val1), Some(val2)) => (val1 + val2) / 2
       case (None, Some(val2)) => val2
       case (Some(val1), None) => val1
       case (None, None) => default
    }
    

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