2012-03-15 73 views
4

此代码确定:小写的变量匹配

val StringManifest = manifest[String] 
val IntManifest = manifest[Int] 

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

但是,如果我们小写变量的第一个字母:

val stringManifest = manifest[String] 
val intManifest = manifest[Int] 

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

我们会得到“无法访问代码”错误。

这种行为的原因是什么?

回答

9

在scala的模式匹配中,小写字母用于匹配器应该是绑定的变量。大写变量或反引号用于现有变量,该变量应该由匹配器使用使用

试试这个:

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

你得到“无法访问代码”错误的原因是,在你的代码,stringManifest是永远绑定到任何manifest是一个变量。由于它始终是绑定的,因此将始终使用该案例,并且将永远不会使用intManifest_个案。

这里展示的行为

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) 
} 

这产生一个简短演示:

matched a 
found 2 
matched A 
+0

感谢伟大的解释! – tokarev 2012-03-15 07:02:57