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:
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?
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.