Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
Mandroid Avatar asked Oct 23 '25 11:10

Mandroid


2 Answers

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.

like image 103
J0HN Avatar answered Oct 26 '25 01:10

J0HN


You could treat the Options as Seq:

val o: Option[Double]
val p: Option[Double]
val default: Double

val s = o.toSeq ++ p.toSeq

val avg = s.reduceOption(_ + _).getOrElse(default) / 1.max(s.size)
like image 42
cbley Avatar answered Oct 26 '25 03:10

cbley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!