加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 模式匹配中的小写变量

发布时间:2020-12-16 09:52:44 所属栏目:安全 来源:网络整理
导读:这段代码工作正常: 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"
}

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

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

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

我们将得到“无法访问的代码”错误.

这种行为的原因是什么?

解决方法

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

试试这个:

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

您收到“无法访问的代码”错误的原因是,在您的代码中,stringManifest是一个始终绑定到任何清单的变量.由于它将始终绑定,因此将始终使用该情况,并且永远不会使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读