编译器如何解释这个?:
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
之间的第一个常见父类(super class)型和 Unit
.请注意,您的大小写匹配是错误的,因为匹配
bar
单独意味着捕获所有变量,您可能想要bar: Bar
.
关于scala - 在 Scala 中有一个 'empty' 的 case 语句是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25843677/