1

Sometimes you may need to perform a match against the current value of a val. The most obvious attempt is not going to work, because the name of the val gets re-bound within the match statement, like this:

  val s = 5                                       //> s  : Int = 5
  val t = 4                                       //> t  : Int = 4
  t match {
    case s => println(s"matched $s")
    case _ => println("outta here!")
  }                                               //> matched 4

What is the most direct way to match against the current value of s?

Daniel Ashton
  • 1,388
  • 11
  • 23
  • 1
    @RobbyCornelissen - When you click the *Ask Question* button, there's a checkbox for *Answer your own question*. [Apparently SO encourages this](http://meta.stackoverflow.com/a/255695/1427124), although I'm not exactly sure why... – DaoWen Jun 15 '14 at 15:19
  • 1
    ... Especially when the question has appeared on SO many times before. This is why SO suggests existing questions as you're typing. – dhg Jun 15 '14 at 15:48
  • Thanks for connecting this question to the earlier one from which I deduced my answer. My hope was that other seekers would be able to find this question if they were searching for the same phrases and terminology I used, such as "current value", which were not turning up results on SO. For programmers who share my programming background, my question and answer here may be easier to find, and more directly answers the question. That was my hope as I posted them. As I leafed through the existing questions suggested by SO, none of them was obviously related to the terms I searched for. – Daniel Ashton Jun 15 '14 at 18:18

1 Answers1

2

Use back-quotes around the name of the val in the case statement:

  val s = 5                                       //> s  : Int = 5
  val t = 4                                       //> t  : Int = 4
  t match {
    case `s` => println(s"matched $s")
    case _ => println("outta here!")
  }                                               //> outta here!
Daniel Ashton
  • 1,388
  • 11
  • 23