在 Scala 中有一个“空”的 case 语句是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25843677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:33:54  来源:igfitidea点击:

What does it mean to have an 'empty' case statement in Scala?

scalasyntax

提问by Core_Dumped

How does the compiler interpret this?:

编译器如何解释这个?:

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

The second case is left empty, with nothing to return.

第二个案例是空的,没有任何回报。

回答by Ende Neu

It means return Unit:

这意味着返回Unit

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

If you change your statement to return something instead of println(which returns Unit):

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

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

Now the compiler has inferred Anybecause it's the first common supertype between Stringand Unit.

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

Note that your case match is wrong because matching on baralone means catch all the variables, you probably wanted bar: Bar.

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

回答by eliasah

The empty defaultcase is necessary in your pattern matching example, because otherwise the match expression would throw a MatchError for every expr argument that is not a bar.

默认情况下是在你的模式匹配例如必要的,因为否则的比赛表达式将抛出每expr参数不是一个酒吧MatchError。

The fact that no code is specified for that second case, so if that case runs it does nothing.

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

The result of either case is the Unit value (), which is also, therefore, the result of the entire match expression.

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

More details on it in Martin Odersky's Programming in Scalabook under Case Classes and Pattern Matchingchapter.

Martin Odersky在Case Classes and Pattern Matching章节下的Programming in Scala书中有更多详细信息。