我有:
val foo = Some(List(1, 2, 3)) -> Some("y")
我想转换匹配它:
foo match {
case (Some(x), Some(y)) => println(x + " " + y)
case _ => println("error")
这适用于
Some(List(1, 2, 3) -> Some("score"))
但失败了 Some(List(1, 2, 3) -> None
, None -> Some("y")
或 None -> None
和:error: constructor cannot be instantiated to expected type;
found : Some[A]
required: None.type
error: not found: value ...
这是为什么?
当然我可以用
getOrElse()
但这看起来并不那么优雅。多谢,
卡斯滕
更新:
foo match {
case (x: Some[List[Int]], y: Some[Int]) => println(x.get)
case _ => println("error")
}
也失败:
error: pattern type is incompatible with expected type;
found : Some[Int]
required: None.type
我认为
case _
会照顾的。
最佳答案
它是编译器告诉你的东西。如果你有一个像
val foo = Some(List(1, 2, 3)) -> None
它将具有类型 (Some[List[Int]], None.type),您可以通过在 Scala 控制台中输入表达式轻松查看
scala> val foo = Some(List(1, 2, 3)) -> None
foo: (Some[List[Int]], None.type) = (Some(List(1, 2, 3)),None)
所以你在编译时知道元组的第二个元素只能是 None,与 Some 的匹配永远不会成功。因此出现错误消息。
如果你给 foo 一个限制较少的类型,它会起作用。
val foo : (Option[List[Int]], Option[String]) = Some(List(1, 2, 3) -> None
请注意,这完全是应该的。匹配永远不会发生的事情几乎肯定是一个错误。您必须向上转换为 any 以避免编译时错误(但随后您将收到运行时错误。
关于Scala - 匹配选项组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165770/