Lower variables in comparison with the sample

This code works fine:

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 introduce the lowercase 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 get an "unreachable code" error.

What are the reasons for this behavior?

+4
source share
1 answer

Compared to the scala pattern, lowercase letters are used for variables that must be matched by match. Top variables or backlinks are used for an existing variable to be used by the connector.

Try this instead:

 def check[T: Manifest] = manifest[T] match { case `stringManifest` => "string" case `intManifest` => "int" case _ => "something else" } 

The reason you get the "Unreachable code" stringManifest is stringManifest there is a variable in your stringManifest code that will always be bound to all manifest . Since it will always bind, this case will always be used, and the intManifest and _ cases will never be used.

Here's a short demo 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 gives:

 matched a found 2 matched A 
+9
source

Source: https://habr.com/ru/post/1401526/


All Articles