Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to yield multiple values?

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

like image 901
SwiftMango Avatar asked Mar 21 '26 13:03

SwiftMango


1 Answers

It should have been unzip, but unfortunately, unzip returns Lists, not Options. 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))
like image 113
Andrey Tyukin Avatar answered Mar 24 '26 01:03

Andrey Tyukin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!