范围内变量的模式匹配 (Scala)
在以下代码中,
val x = 5
val y = 4 match {
case x => true
case _ => false
}
值 y
为 true。 Scala 将 x
解释为模式匹配中的自由变量,而不是将其绑定到作用域中具有相同名称的变量。
如何解决这个问题呢?
In the following code
val x = 5
val y = 4 match {
case x => true
case _ => false
}
the value y
is true. Scala interprets x
to be a free variable in the pattern match instead of binding it to the variable with the same name in the scope.
How to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反引号变量表示绑定作用域变量:
返回
false
。或者,如果变量以大写字母开头,则它会绑定到作用域变量而不用反引号。
Backticking the variable indicates to bind a scoped variable:
returns
false
.Alternatively, if a variable starts with an uppercase letter, it binds to a scoped variable without backticking.
援引最少惊讶原则,我会简单地这样做:
Invoking the least astonishment principle, I will simply do: