模式匹配中的小写变量

时间:2012-03-15 05:22:13

标签: scala

此代码可以正常工作:

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

我们将收到“无法访问的代码”错误。

这种行为的原因是什么?

1 个答案:

答案 0 :(得分: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
相关问题