String (模式)与Scala中的字符串匹配

String (模式)与Scala中的字符串匹配,string,scala,pattern-matching,String,Scala,Pattern Matching,我想将一个给定的字符串与一组给定的其他字符串进行比较。我没有使用一系列的ifs,而是采用了更简洁的模式匹配方法,直观地写道: 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")

我想将一个给定的字符串与一组给定的其他字符串进行比较。我没有使用一系列的
if
s,而是采用了更简洁的模式匹配方法,直观地写道:

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")
}
令我惊讶的是,这导致:

Incorrect match 1

我的编译器警告beyond
cases2=>…
我的代码无法访问。为什么我的方法不起作用?我怎样才能“匹配”一个字符串呢?

这个带有模式匹配的小写变量在Scala中,会被认为是一个新的临时变量。这导致您的代码将输出不正确的匹配项1。因此,您可以使用
标识符
对变量进行编码以匹配其值,如:

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

或者您可以将变量名更新为大写,例如:
S1
S2
S3
,这个小写变量与Scala中的模式匹配,它将被认为是一个新的临时变量。这导致您的代码将输出不正确的匹配项1。因此,您可以使用
标识符
对变量进行编码以匹配其值,如:

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

或者,您可以将变量名更新为大写,例如:
S1
S2
S3

是否需要模式匹配?是的,简化了示例以解决我的问题。是否需要模式匹配?是的,简化了示例以解决我的问题。