我正在尝试在 Java Class[_] 上使用 Scala 模式匹配(在使用来自 Scala 的 Java 反射的上下文中),但我遇到了一些意外错误。以下给出了 行上的“无法访问的代码”案例jLong
def foo[T](paramType: Class[_]): Unit = {
val jInteger = classOf[java.lang.Integer]
val jLong = classOf[java.lang.Long]
paramType match {
case jInteger => println("int")
case jLong => println("long")
}
}
任何想法为什么会发生这种情况?
最佳答案
如果您将变量名称更改为大写(或在模式中用反引号将它们括起来),代码将按预期工作:
scala> def foo[T](paramType: Class[_]): Unit = {
| val jInteger = classOf[java.lang.Integer]
| val jLong = classOf[java.lang.Long]
| paramType match {
| case `jInteger` => println("int")
| case `jLong` => println("long")
| }
| }
foo: [T](paramType: Class[_])Unit
scala> foo(classOf[java.lang.Integer])
int
在您的代码中 jInteger
在第一个模式中是一个新变量——它不是 jInteger
从周围的范围。来自 specification :8.1.1 Variable Patterns
... A variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value.
...
8.1.5 Stable Identifier Patterns
... To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter. However, it is possible to enclose a such a variable name in backquotes; then it is treated as a stable identifier pattern.
见 this question了解更多信息。
关于scala - Class[_] 类型的模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519140/