Why does pattern matching in Scala not work with variables?

ScalaPattern MatchingMatch

Scala Problem Overview


Take the following function:

def fMatch(s: String) = {
    s match {
        case "a" => println("It was a")
        case _ => println("It was something else")
    }
}

This pattern matches nicely:

scala> fMatch("a")
It was a

scala> fMatch("b")
It was something else

What I would like to be able to do is the following:

def mMatch(s: String) = {
    val target: String = "a"
    s match {
        case target => println("It was" + target)
        case _ => println("It was something else")
        }
}

This gives off the following error:

fMatch: (s: String)Unit
<console>:12: error: unreachable code
               case _ => println("It was something else")

I guess this is because it thinks that target is actually a name you'd like to assign to whatever the input is. Two questions:

  1. Why this behaviour? Can't case just look for existing variables in scope that have appropriate type and use those first and, if none are found, then treat target as a name to patternmatch over?

  2. Is there a workaround for this? Any way to pattern match against variables? Ultimately one could use a big if statement, but match case is more elegant.

Scala Solutions


Solution 1 - Scala

What you're looking for is a stable identifier. In Scala, these must either start with an uppercase letter, or be surrounded by backticks.

Both of these would be solutions to your problem:

def mMatch(s: String) = {
    val target: String = "a"
    s match {
        case `target` => println("It was" + target)
        case _ => println("It was something else")
    }
}

def mMatch2(s: String) = {
    val Target: String = "a"
    s match {
        case Target => println("It was" + Target)
        case _ => println("It was something else")
    }
}

To avoid accidentally referring to variables that already existed in the enclosing scope, I think it makes sense that the default behaviour is for lowercase patterns to be variables and not stable identifiers. Only when you see something beginning with upper case, or in back ticks, do you need to be aware that it comes from the surrounding scope.

Solution 2 - Scala

You can also assign it to a temporary variable inside the case and then compare it, that will also work

def mMatch(s: String) = {
    val target: String = "a"
    s match {
        case value if (value ==target) => println("It was" + target) //else {} optional
        case _ => println("It was something else")
    }
}


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHenry HenrinsonView Question on Stackoverflow
Solution 1 - ScalaBen JamesView Answer on Stackoverflow
Solution 2 - ScalaRaptor0009View Answer on Stackoverflow