I have a for comprehension like:
val ao = Option(1)
val bo = Option(2)
val (x,y) = for (a <- ao; b <- bo) yield (a+b, b+a*2)
However this does not work. For comprehension returns Option[(Int,Int)]
but cannot be assigned to individual x and y.
If I do:
val Some((x,y)) = for ...
It causes exception when yield None.
How to achieve this goal? I want x and y to be Option[Int]
. I hope to find an elegant solution without using like x._1
or x.getOrElse
, or match
It should have been unzip
, but unfortunately, unzip
returns List
s, not Option
s. Probably the shortest work-around would be:
val pairOpt = for (a <- ao; b <- bo) yield (a+b, b+a*2)
val (x, y) = (pairOpt.map(_._1), pairOpt.map(_._2))