Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on Class[_] type?

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 ?

like image 879
alphageek Avatar asked Sep 22 '11 17:09

alphageek


1 Answers

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.

like image 153
Travis Brown Avatar answered Nov 16 '22 01:11

Travis Brown