I have two variables that are optional double and I want to consider them as 0 when they are None
var x: Option[Double] = Option(0)
var y: Option[Double] = Option(0)
println("Expected 0 : "+(x ++ y).reduceOption(_ - _)) // 0
x = Option(4)
y = Option(0)
println("Expected 4 : "+(x ++ y).reduceOption(_ - _)) // 4
x = Option(0)
y = Option(4)
println("Expected -4 : "+(x ++ y).reduceOption(_ - _)) // -4
x = Option(4)
y = None
println("Expected 4 : "+(x ++ y).reduceOption(_ - _)) // 4
x = None
y = Option(4.0)
println("Expected -4 : "+(x ++ y).reduceOption(_ - _)) // 4
The last one I am expecting -4 but I get 4.
If I use
(for (i <- x; j <- y) yield i - j)
then I get None.
Also If I try
x.getOrElse(0) - y.getOrElse(0) // value - is not a member of AnyVal
then I get error value - is not a member of AnyVal
The
(x ++ y).reduceOption(_ - _)is a perfect example of how to confuse people in Scala IMHO. It's not immediate that++operates onOptionbecause they are alsoSeq.That being said, as already suggested in the comments, the straightforward way would be to use
getOrElse:You need to precise the
dto have anDoubleotherwise, you get anAnyValbecauseAnyValis the only common parent type ofInt(from thegetOrElse) andDouble(value in the option).