模式匹配中的小写变量 [英] lowercased variables in pattern matching
问题描述
此代码运行正常:
val StringManifest = manifest[String]
val IntManifest = manifest[Int]
def check[T: Manifest] = manifest[T] match {
case StringManifest => "string"
case IntManifest => "int"
case _ => "something else"
}
但是如果我们小写变量的第一个字母:
But if we lowercase the first letter of the variables:
val stringManifest = manifest[String]
val intManifest = manifest[Int]
def check[T: Manifest] = manifest[T] match {
case stringManifest => "string"
case intManifest => "int"
case _ => "something else"
}
我们会收到unreachable code"错误.
we will get "unreachable code" error.
这种行为的原因是什么?
What are the reasons of this behavior?
推荐答案
在 scala 的模式匹配中,小写用于应该由匹配器绑定的变量.大写变量或反引号用于匹配器应该使用的现有变量.
In scala's pattern matching, lowercase is used for variables that should be bound by the matcher. Uppercase variables or backticks are used for existing variable that should be used by the matcher.
试试这个:
def check[T: Manifest] = manifest[T] match {
case `stringManifest` => "string"
case `intManifest` => "int"
case _ => "something else"
}
您收到Unreachable code"错误的原因是,在您的代码中,stringManifest
是一个始终绑定到任何 manifest
的变量.由于它将始终绑定,因此将始终使用该案例,并且永远不会使用 intManifest
和 _
案例.
The reason you're getting the "Unreachable code" error is that, in your code, stringManifest
is a variable that will always bind to whatever manifest
is. Since it will always bind, that case will always be used, and the intManifest
and _
cases will never be used.
这是显示行为的简短演示
Here's a short demonstration showing the behavior
val a = 1
val A = 3
List(1,2,3).foreach {
case `a` => println("matched a")
case A => println("matched A")
case a => println("found " + a)
}
这产生:
matched a
found 2
matched A
这篇关于模式匹配中的小写变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!