如何在Scala中解压Option[(Int,Int)]
以下是用于解压缩返回值的有效且可读的代码段。
def func: (Int, Int) = (1, 2)
val (a, b) = func
返回的函数Option呢?例如:
def func2: Option[(Int, Int)] = Some((1, 2))
我怎样才能以可读的方式解压它?
回答
请注意,这(Int, Int)是元组类型的糖
Tuple2[Int, Int]
于是Option[(Int, Int)]变成
Option[Tuple2[Int, Int]]
因此正确的语法是
val Some(Tuple2(a, b)) = func2
或者
val Some((a, b)) = func2
或者
val Some(a -> b) = func2
但是请注意,如果func2返回,None则它将与MatchError. 如果我们检查类似的扩展版本,原因就很清楚了
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
请注意我们没有处理None案例。由于这个原因,很少进行这种提取。通常我们会映射Option并在上下文中继续工作Option
func2.map { case (a, b) =>
// work with a and b
}
或者如果可能的话我们提供一些默认值
val (a, b) = func2.getOrElse((0, 0))
- I believe it would good to do more emphasis on the failure possibility of this operation, I would even mention it at the very beginning. A tuple is always total, so unpacking it makes sense. An **Option** is not, maybe it would be also good to include `getOrElse` in the answer.