为什么Scala中的模式匹配不适用于变量?
采取以下功能:
def fMatch(s: String) = {
s match {
case "a" => println("It was a")
case _ => println("It was something else")
}
}
这种模式很好匹配:
scala> fMatch("a")
It was a
scala> fMatch("b")
It was something else
我希望能够做到的是以下几点:
def mMatch(s: String) = {
val target: String = "a"
s match {
case target => println("It was" + target)
case _ => println("It was something else")
}
}
这给出了以下错误:
fMatch: (s: String)Unit
<console>:12: error: unreachable code
case _ => println("It was something else")
我想这是因为它认为目标实际上是你想分配给任何输入的名称。 两个问题:
为什么会这样? 不能仅仅查找范围中具有适当类型的现有变量并首先使用它们,如果没有找到,然后将目标作为模式匹配的名称来处理?
有没有解决方法? 任何模式匹配变量的方式? 最终可以使用大的if语句,但是匹配大小更优雅。
你正在寻找的是一个稳定的标识符 。 在斯卡拉,这些必须以大写字母开头,或者用反引号包围。
这两个都可以解决您的问题:
def mMatch(s: String) = {
val target: String = "a"
s match {
case `target` => println("It was" + target)
case _ => println("It was something else")
}
}
def mMatch2(s: String) = {
val Target: String = "a"
s match {
case Target => println("It was" + Target)
case _ => println("It was something else")
}
}
为了避免意外地引用已经存在于封闭范围中的变量,我认为有意义的是,默认行为是将小写模式作为变量而不是稳定标识符。 只有当你看到以大写字母开头的东西或者后面的蜱时,你是否需要意识到它来自周围的范围。
链接地址: http://www.djcxy.com/p/62629.html上一篇: Why does pattern matching in Scala not work with variables?
下一篇: Using comparison operators in Scala's pattern matching system