(模式)匹配Scala中的字符串[重复]

问题描述 投票:0回答:1

我想将给定的字符串与给定的其他字符串集进行比较。我没有使用一系列的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")
  case s3 => println("Match")
  case _ => println("Another incorrect match")
}

令我惊讶的是,这导致:

Incorrect match 1

我的编译器警告说,除了case s2 =>...我的代码无法访问。为什么我的方法不起作用?我如何“匹配”字符串?

string scala pattern-matching
1个回答
2
投票

这个小写变量与Scala中的模式匹配,它将被认为是一个新的临时变量。这导致您的代码将输出Incorrect match 1。因此,您可以使用identifier对变量进行编码以匹配其值,例如:

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

或者您可以将变量名称更新为大写,例如:S1S2S3

© www.soinside.com 2019 - 2024. All rights reserved.