范围内变量的模式匹配 (Scala)

发布于 2024-11-25 06:51:54 字数 223 浏览 3 评论 0原文

在以下代码中,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

究竟谁懂我的在乎 2024-12-02 06:51:54

反引号变量表示绑定作用域变量:

val x = 5
val y = 4 match { case `x` => true; case _ => false }

返回 false

或者,如果变量以大写字母开头,则它会绑定到作用域变量而不用反引号。

Backticking the variable indicates to bind a scoped variable:

val x = 5
val y = 4 match { case `x` => true; case _ => false }

returns false.

Alternatively, if a variable starts with an uppercase letter, it binds to a scoped variable without backticking.

維他命╮ 2024-12-02 06:51:54

援引最少惊讶原则,我会简单地这样做:

val x = 5
val y = 4 match {
  case z if z == x => true
  case _ => false
}

Invoking the least astonishment principle, I will simply do:

val x = 5
val y = 4 match {
  case z if z == x => true
  case _ => false
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文