Pattern matching on Class[_] type?

不羁岁月 提交于 2020-05-08 20:48:11

问题


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")
  }
}

Any ideas why this is happening ?


回答1:


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

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

See this question for more information.




回答2:


On your pattern matching, each of these 2 cases try to create place holder names instead of matching the class type as expected.

If you use upper case in the starting character, you'll be fine

def foo[T](paramType: Class[_]): Unit = {
  val JInteger = classOf[Int]
  val JLong = classOf[Long]
  paramType match {
    case JInteger => println("int")
    case JLong => println("long")
  }
}

scala> foo(1.getClass)
int


来源:https://stackoverflow.com/questions/7519140/pattern-matching-on-class-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!