Class[_] 类型的模式匹配? [英] Pattern matching on Class[_] type?

查看:41
本文介绍了Class[_] 类型的模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Java Class[_] 上使用 Scala 模式匹配(在使用来自 Scala 的 Java 反射的上下文中),但出现了一些意外错误.下面给出了case jLong

I'm trying to use Scala pattern matching on Java Class[_] (in context of using Java reflection from Scala) but I'm getting some unexpected error. The following gives "unreachable code" on the line with case 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")
  }
}

知道为什么会这样吗?

推荐答案

如果您将变量名称更改为大写(或在模式中用反引号将它们括起来),代码将按预期工作:

The code works as expected if you change the variable names to upper case (or surround them with backticks in the pattern):

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.来自规范:

In your code the jInteger in the first pattern is a new variable—it's not the jInteger from the surrounding scope. From the specification:

8.1.1 变量模式

... 变量模式 x 是一个以小写字母开头的简单标识符.它匹配任何值,并将变量名绑定到该值.

... 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 稳定的标识符模式

... 用可变模式解决句法重叠,稳定标识符模式可能不是以小写字母开头的简单名称信件.但是,可以将这样的变量名称包含在反引号;然后将其视为稳定的标识符模式.

... 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.

有关详细信息,请参阅此问题.

See this question for more information.

这篇关于Class[_] 类型的模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆