Pattern match for variable in scope (Scala)

放肆的年华 提交于 2020-01-11 02:50:26

问题


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?


回答1:


Invoking the least astonishment principle, I will simply do:

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



回答2:


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.



来源:https://stackoverflow.com/questions/6754579/pattern-match-for-variable-in-scope-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!