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

查看:93
本文介绍了为什么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. 为什么这种行为?不能仅在范围内查找具有适当类型的现有变量并先使用那些变量,如果找不到,然后将target视为模式匹配的名称吗?

  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语句,但是匹配大小写更为优雅.

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天全站免登陆