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?

2
  • 3
    Why did you duplicate an existing question and then answer it yourself? stackoverflow.com/questions/6172557/… stackoverflow.com/questions/5153590/… Commented Jul 19, 2011 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. Commented Jul 21, 2011 at 7:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
}

2 Comments

Ron answer is the good one, you add a condition that can be pattern matched directly. (downvote)
I think the condition is just as fast, and remember the least astonishment principle. (upvote)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.