为什么 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")
我想这是因为它认为目标实际上是您想要分配给的名称无论输入是什么。两个问题:
为什么会出现这种行为? case 不能只查找范围内具有适当类型的现有变量并首先使用这些变量,如果没有找到,则将 target 视为模式匹配的名称?
有解决办法吗?有什么方法可以对变量进行模式匹配吗?最终,我们可以使用一个大的 if 语句,但匹配大小写更优雅。
Take the following function:
def fMatch(s: String) = {
s match {
case "a" => println("It was a")
case _ => println("It was something else")
}
}
This pattern matches nicely:
scala> fMatch("a")
It was a
scala> fMatch("b")
It was something else
What I would like to be able to do is the following:
def mMatch(s: String) = {
val target: String = "a"
s match {
case target => println("It was" + target)
case _ => println("It was something else")
}
}
This gives off the following error:
fMatch: (s: String)Unit
<console>:12: error: unreachable code
case _ => println("It was something else")
I guess this is because it thinks that target is actually a name you'd like to assign to whatever the input is. Two questions:
Why this behaviour? Can't case just look for existing variables in scope that have appropriate type and use those first and, if none are found, then treat target as a name to patternmatch over?
Is there a workaround for this? Any way to pattern match against variables? Ultimately one could use a big if statement, but match case is more elegant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的是稳定标识符。在 Scala 中,它们必须以大写字母开头,或者用反引号括起来。
这两个都可以解决您的问题:
为了避免意外引用封闭范围中已经存在的变量,我认为默认行为是小写模式是变量而不是稳定的标识符是有意义的。仅当您看到以大写字母开头或以反引号开头的内容时,您才需要意识到它来自周围的范围。
What you're looking for is a stable identifier. In Scala, these must either start with an uppercase letter, or be surrounded by backticks.
Both of these would be solutions to your problem:
To avoid accidentally referring to variables that already existed in the enclosing scope, I think it makes sense that the default behaviour is for lowercase patterns to be variables and not stable identifiers. Only when you see something beginning with upper case, or in back ticks, do you need to be aware that it comes from the surrounding scope.
您也可以将其分配给案例内的临时变量,然后比较它,这也可以
You can also assign it to a temporary variable inside the case and then compare it, that will also work