Pattern matching on Class[_] type?
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
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.