Scala - 匹配选项组

标签 scala pattern-matching option

我有:

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/

相关文章:

scala - 映射到相同类型的 Traversable 的 Traversable 类型

unit-testing - 使用 Scala 2.10.2、SBT 0.13.0、Specs2 和 Play Framework 2.2.1 如何在运行测试时控制日志记录?

enums - 匹配时修改枚举中的值

scala - 如何将可以为 null 或数组的值隐式包装到 Scala 选项中

Scala:除了空选项之外,将 None 用于其他目的

scala - Akka websocket - 如何通过服务器关闭连接?

java - scala 与 java 中的导入类优先级

algorithm - 有没有办法从更大的矩阵中匹配子矩阵?

元组类型上的 F# 模式匹配

javascript - 我的选择列表中的所有选项都连接在一个大选项中。我该如何解决?