Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala two options defined, return first, else return second

Tags:

scala

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

like image 819
Dean Hiller Avatar asked Jun 09 '15 19:06

Dean Hiller


1 Answers

You can use pattern matching :

(optionA, optionB) match {
  case (Some(_), Some(_)) => optionA
  case _ => optionB
}
like image 50
Marth Avatar answered Nov 07 '22 13:11

Marth