user404345
user404345

Reputation:

Optional tuple to tuple of options

In scala is there an easy way to transform an optional tuple into a tuple of options i.e

Option[(Int, Int)] => (Option[Int], Option[Int])

Thanks

p.s. now I am just using:

val myTuple: Option[(Int, Int)] = Some((1, 1))
if (myTuple.isDefined) 
  (Some(myTuple.get._1), Some(myTuple.get._2)) 
else 
  (None, None)

Upvotes: 2

Views: 842

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

val myTuple: Option[(A, B)] = ...
(myTuple.map(_._1), myTuple.map(_._2))

Upvotes: 1

Dima
Dima

Reputation: 40500

Something like this maybe (not that it is much "easier" than what you have, but more idiomatic):

 option.map { case (a,b) => Some(a) -> Some(b) }.getOrElse(None -> None)

Upvotes: 3

Related Questions