Reputation: 339
Hey I'm having difficulty with getting values from a tuple
I want to do arithmetic operations on the values of two Option[Double] if they are not equal to None. The code I have so far is this
def optionDoubleAddition(a: Option[Double], b: Option[Double]) : Option[Double] = {
val tuple = if(a != None && b != None) (a.getOrElse(0: Double),b.getOrElse(0: Double))
println(tuple) //prints the values correctly when passed two doubles
None //something to make the function work
}
It won't allow me to get the single elements from the tuple with either
println(t(0))
println(t._1)
Also I'm a bit concerned with the getOrElse function is there any alternative to this, i've tried solving the above in different ways for example if i wanted to do the following
val example: Option[Double] = Some(5.0)
and I want to get the value of example or None otherwise
example.getOrElse(None)
which returns the value as Any however I need it to be a double, if i try the following I also run into errors if it is None
val doubleValue: Double = example.getOrElse(None)
Thanks!
Upvotes: 0
Views: 71
Reputation: 51271
I think this is what you're looking for, at least it is correct for the method profile.
def optionDoubleAddition(a: Option[Double], b: Option[Double]) : Option[Double] =
for {x <- a; y <- b} yield x+y
This unwraps each Option
, adds them, and re-wraps the result, but if either or both is None
then the unwrapping stops and None
is returned.
Upvotes: 3