If I have optionA, and optionB, how can I return optionA if both are defined and optionB is both are not defined.
Basically, I am trying to rewrite this
val result: Option[Long] =
if(optionA.isDefined && optionB.isDefined)
optionA
else
optionB
No, optionA.orElse(optionB) is not the same and broke our test cases. BOTH options must be defined and we want to use optionA. IF optionA is defined and optionB is not defined, we want None.
Someone marked my question as a duplicate which it is not. I was having trouble but finally stumbled upon the answer....
ok, I think I got it and I definitely think it is less human readable
optionA.flatMap { aId =>
optionB.map(bId => bId).orElse(Some(aId))
}
for added clarity. our truth table is thus
optionA.isDefined optionB.isDefined resultNeeded
None None None
Some(a) None None
None Some(b) Some(b)
Some(a) Some(b) Some(a)
thanks
You can use pattern matching :
(optionA, optionB) match {
case (Some(_), Some(_)) => optionA
case _ => optionB
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With