6

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?

ron
  • 9,262
  • 4
  • 40
  • 73
  • 3
    Why did you duplicate an existing question and then answer it yourself? http://stackoverflow.com/questions/6172557/problem-with-scala-matching-scope http://stackoverflow.com/questions/5153590/why-does-scala-complain-when-given-this-pattern-match-on-an-integral-value – dhg Jul 19 '11 at 23:08
  • @dhg: I could not find that question on SO, that's why. I answer my own question since I prefer using SO as a knowledge repository instead of taking a note on my tiny hidden blog or making a mental post. Thanks for the link, I agree with closing with duplicate. – ron Jul 21 '11 at 07:41

2 Answers2

12

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.

ron
  • 9,262
  • 4
  • 40
  • 73
  • see also http://scala-programming-language.1934581.n4.nabble.com/scala-pattern-matching-proposal-td1999364.html – ron Jul 19 '11 at 21:51
7

Invoking the least astonishment principle, I will simply do:

val x = 5
val y = 4 match {
  case z if z == x => true
  case _ => false
}
paradigmatic
  • 40,153
  • 18
  • 88
  • 147