Matching a pattern for a variable in an area (Scala)

In the following code

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

the value is ytrue. Scala interprets it xas a free variable in pattern matching instead of binding to a variable with the same name in the scope.

How to solve this problem?

+5
source share
2 answers

Calling on the principle of least surprise, I will simply do:

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

Returning the variable indicates the binding of the changed area:

val x = 5
val y = 4 match { case `x` => true; case _ => false }

returns false.

Alternatively, if a variable begins with an uppercase letter, it binds to the variable with an area without a back binding.

+12
source

All Articles