gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:49:48 25 4
gpt4 key购买 nike

此代码工作正常:

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 的模式匹配中,小写用于应该由匹配器绑定(bind)的变量。大写变量或反引号用于匹配器应该使用的现有变量。

试试这个:

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

您收到“无法访问的代码”错误的原因是,在您的代码中, stringManifest是一个始终绑定(bind)到任何 manifest 的变量。是。由于它将始终绑定(bind),因此将始终使用该案例,并且 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

关于scala - 模式匹配中的小写变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com