This code works OK:
val StringManifest = manifest[String]
val IntManifest = manifest[Int]
def check[T: Manifest] = manifest[T] match {
case StringManifest => "string"
case IntManifest => "int"
case _ => "something else"
}
But if we lowercase the first letter of the variables:
val stringManifest = manifest[String]
val intManifest = manifest[Int]
def check[T: Manifest] = manifest[T] match {
case stringManifest => "string"
case intManifest => "int"
case _ => "something else"
}
we will get "unreachable code" error.
What are the reasons of this behavior?
In scala's pattern matching, lowercase is used for variables that should be bound by the matcher. Uppercase variables or backticks are used for existing variable that should be used by the matcher.
Try this instead:
def check[T: Manifest] = manifest[T] match {
case `stringManifest` => "string"
case `intManifest` => "int"
case _ => "something else"
}
The reason you're getting the "Unreachable code" error is that, in your code, stringManifest
is a variable that will always bind to whatever manifest
is. Since it will always bind, that case will always be used, and the intManifest
and _
cases will never be used.
Here's a short demonstration showing the behavior
val a = 1
val A = 3
List(1,2,3).foreach {
case `a` => println("matched a")
case A => println("matched A")
case a => println("found " + a)
}
This yields:
matched a
found 2
matched A