开发者

Pattern match for variable in scope (Scala)

开发者 https://www.devze.com 2023-03-21 18:22 出处:网络
In the following c开发者_JAVA技巧ode val x = 5 val y = 4 match { case x => true case _ => false

In the following c开发者_JAVA技巧ode

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?


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.


Invoking the least astonishment principle, I will simply do:

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

精彩评论

暂无评论...
验证码 换一张
取 消