【问题标题】:What does it mean to have an 'empty' case statement in Scala?在 Scala 中有一个“空”的 case 语句是什么意思?
【发布时间】:2014-09-15 08:25:01
【问题描述】:

编译器如何解释这个?:

foo match {
  case bar: Bar => println("First case statement")
  case _ => 
}

第二种情况是空的,没有任何东西可以返回。

【问题讨论】:

    标签: scala syntax


    【解决方案1】:

    表示返回Unit:

    val res: Unit = new foo match {
      case bar: Bar => println("First case statement")
      case _ =>
    }
    

    如果您更改语句以返回某些内容而不是 println(返回 Unit):

    val res: Any = new foo match {
      case bar: Bar => "it's a bar"
      case _ =>
    }
    

    现在编译器已经推断出Any,因为它是StringUnit 之间的第一个公共超类型。

    请注意,您的大小写匹配是错误的,因为单独匹配 bar 意味着捕获所有变量,您可能想要 bar: Bar

    【讨论】:

      【解决方案2】:

      default 在您的模式匹配示例中是必要的,否则 match 表达式会为每个不是 bar 的 expr 参数抛出 MatchError。

      没有为第二种情况指定代码这一事实,因此如果该情况运行,它什么也不做。

      任何一种情况的结果都是 Unit 值 (),因此它也是整个匹配表达式的结果。

      Martin Odersky 的Scala 编程一书中的Case Classes and Pattern Matching一章中有更多详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2011-11-18
        • 2011-08-15
        • 2016-10-03
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多