Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match for variable in scope (Scala)

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?

like image 930
ron Avatar asked Jul 19 '11 21:07

ron


1 Answers

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.

like image 137
ron Avatar answered Oct 21 '22 18:10

ron