最佳答案
履行以下职能:
def fMatch(s: String) = {
s match {
case "a" => println("It was a")
case _ => println("It was something else")
}
}
这种模式非常匹配:
scala> fMatch("a")
It was a
scala> fMatch("b")
It was something else
我希望能够做到以下几点:
def mMatch(s: String) = {
val target: String = "a"
s match {
case target => println("It was" + target)
case _ => println("It was something else")
}
}
这会产生以下错误:
fMatch: (s: String)Unit
<console>:12: error: unreachable code
case _ => println("It was something else")
我猜这是因为它认为 target 实际上是您希望分配给任何输入的名称。两个问题:
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?
有解决办法吗?有没有什么方法可以对变量进行模式匹配?最终,我们可以使用一个大的 if 语句,但匹配用例更优雅。