【发布时间】:2014-09-15 08:25:01
【问题描述】:
编译器如何解释这个?:
foo match {
case bar: Bar => println("First case statement")
case _ =>
}
第二种情况是空的,没有任何东西可以返回。
【问题讨论】:
编译器如何解释这个?:
foo match {
case bar: Bar => println("First case statement")
case _ =>
}
第二种情况是空的,没有任何东西可以返回。
【问题讨论】:
表示返回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,因为它是String 和Unit 之间的第一个公共超类型。
请注意,您的大小写匹配是错误的,因为单独匹配 bar 意味着捕获所有变量,您可能想要 bar: Bar。
【讨论】:
空 default 在您的模式匹配示例中是必要的,否则 match 表达式会为每个不是 bar 的 expr 参数抛出 MatchError。
没有为第二种情况指定代码这一事实,因此如果该情况运行,它什么也不做。
任何一种情况的结果都是 Unit 值 (),因此它也是整个匹配表达式的结果。
Martin Odersky 的Scala 编程一书中的Case Classes and Pattern Matching一章中有更多详细信息。
【讨论】: