1

I want to compare a given string to a given set of other strings. Instead of using a series of ifs I went for the more concise pattern matching way, and intuitively wrote:

val s = "match"

val s1 = "not match"
val s2 = "not really a match"
val s3 = "match"

s match {
  case s1 => println("Incorrect match 1")
  case s2 => println("Incorrect match 2")
  case s3 => println("Match")
  case _ => println("Another incorrect match")
}

Which, surprisingly to me, resulted in:

Incorrect match 1

And my compiler warning that beyond case s2 =>... my code is unreachable. Why doesn't my approach work? And how can I "match" against a string?

parazs
  • 43
  • 3

1 Answers1

3

This lowercase variable with pattern match in Scala, it will be thought it's a new temp variable. that's caused your code will output Incorrect match 1. so you can use an identifier to encode your variable to match their value, like:

  s match {
    case `s1` => println("Incorrect match 1")
    case `s2` => println("Incorrect match 2")
    case `s3` => println("Match") 

or you can update your variable name to uppercase, like to: S1, S2, S3

chengpohi
  • 14,064
  • 1
  • 24
  • 42