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 ?
The code works as expected if you change the variable names to upper case (or surround them with backticks in the pattern):
In your code the
jIntegerin the first pattern is a new variable—it’s not thejIntegerfrom the surrounding scope. From the specification:See this question for more information.