为什么 Scala 中的模式匹配不适用于变量? [英] Why does pattern matching in Scala not work with variables?

查看:25
本文介绍了为什么 Scala 中的模式匹配不适用于变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下函数:

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")

我猜这是因为它认为目标实际上是您想分配给任何输入的名称.两个问题:

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:

  1. 为什么会有这种行为?不能只在范围内查找具有适当类型的现有变量并首先使用它们,如果没有找到,则将目标视为名称以进行模式匹配吗?

  1. 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 语句,但 match case 更优雅.

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.

推荐答案

您正在寻找的是稳定标识符.在 Scala 中,它们必须以大写字母开头,或者被反引号包围.

What you're looking for is a stable identifier. In Scala, these must either start with an uppercase letter, or be surrounded by backticks.

这两种方法都可以解决您的问题:

Both of these would be solutions to your problem:

def mMatch(s: String) = {
    val target: String = "a"
    s match {
        case `target` => println("It was" + target)
        case _ => println("It was something else")
    }
}

def mMatch2(s: String) = {
    val Target: String = "a"
    s match {
        case Target => println("It was" + Target)
        case _ => println("It was something else")
    }
}

为了避免意外引用封闭作用域中已经存在的变量,我认为默认行为是小写模式是变量而不是稳定标识符是有道理的.只有当您看到以大写字母开头或以反引号开头的内容时,您才需要意识到它来自周围的范围.

To avoid accidentally referring to variables that already existed in the enclosing scope, I think it makes sense that the default behaviour is for lowercase patterns to be variables and not stable identifiers. Only when you see something beginning with upper case, or in back ticks, do you need to be aware that it comes from the surrounding scope.

这篇关于为什么 Scala 中的模式匹配不适用于变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆