Alperen
Alperen

Reputation: 4602

How to unpack Option[(Int, Int)] in Scala

The following is a valid and readable piece of code to unpack returned values.

def func: (Int, Int) = (1, 2)

val (a, b) = func

What about the functions that return Option? For example:

def func2: Option[(Int, Int)] = Some((1, 2))

How can I unpack this in a readable way?

Upvotes: 1

Views: 218

Answers (1)

Mario Galic
Mario Galic

Reputation: 48410

Note that (Int, Int) is sugar for tuple type

Tuple2[Int, Int]

so Option[(Int, Int)] becomes

Option[Tuple2[Int, Int]]

thus correct syntax would be

val Some(Tuple2(a, b)) = func2

or

val Some((a, b)) = func2

or

val Some(a -> b) = func2

However mind if func2 returns None then it will explode with MatchError. The reason becomes clear if we examine the expanded version which is something like

val x: (Int, Int) = func2 match {
  case Some((a, b)) => (a, b)
  // but what about None case ??
}

val a = x._1
val b = x._2

Note how we did not handle None case. For this reason such extraction is rarely done. Usually we map over the Option and continue working within the context of the Option

func2.map { case (a, b) => 
  // work with a and b
}

or we provide some default value if possible

val (a, b) = func2.getOrElse((0, 0))

Upvotes: 5

Related Questions