Scala 模式匹配小写变量名 [英] Scala pattern matching with lowercase variable name

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

问题描述

我发现当使用模式匹配与替代(对于字符串)时,Scala 接受以大写开头的变量(在下面的示例中,MyValue1MyValue2),但是不是那些以小写开头的 (myValue1, myValue2).这是 Scala 的错误还是特性?我在 2.8 版中得到了这个.如果这是一个功能,任何人都可以解释其背后的基本原理吗?这是我使用的代码:

I found that when using pattern matching with alternatives (for strings), Scala accepts variables starting with upper case (in the example below, MyValue1 and MyValue2), but not those starting with lower case (myValue1, myValue2). Is this a bug or a feature of Scala? I get this in version 2.8. If this is a feature, can anyone explain the rationale behind it? This is the code I used:

val myValue1 = "hello"
val myValue2 = "world"
val MyValue1 = "hello"
val MyValue2 = "world"

var x:String = "test"

x match {
  case MyValue1 | MyValue2 => println ("first match")
  case myValue1 | myValue2 => println ("second match")
}

运行时,我得到以下信息:

On running, I get the following:

scala> val myValue1 = "hello"
myValue1: java.lang.String = hello

scala> val myValue2 = "world"
myValue2: java.lang.String = world

scala> val MyValue1 = "hello"
MyValue1: java.lang.String = hello

scala> val MyValue2 = "world"
MyValue2: java.lang.String = world

scala> var x:String = "test"
x: String = test

scala> x match {
 |   case MyValue1 | MyValue2 => println ("first match")
 |   case myValue1 | myValue2 => println ("second match")
 | }
<console>:11: error: illegal variable in pattern alternative
     case myValue1 | myValue2 => println ("second match")
          ^
<console>:11: error: illegal variable in pattern alternative
     case myValue1 | myValue2 => println ("second match")
                     ^

编辑:

所以它确实是一个功能而不是一个错误......任何人都可以提供一个可能有用的例子吗?

So it is indeed a feature and not a bug... Can anyone provide an example when this might be useful?

当我使用时:

x match {
   case myValue1 => println ("match")
   case _ => 
}

我在最后一种情况下收到 unreachable code 警告,这意味着第一个总是匹配的.

I get an unreachable code warning on the last case, implying that the first one always matches.

推荐答案

这不是特定于具有替代方案的模式,也不是错误.模式中以小写字母开头的标识符表示如果模式匹配则将绑定的新变量.

This is not specific to patterns with alternatives, and it is not a bug. An identifier that begins with a lowercase letter in a pattern represents a new variable that will be bound if the pattern matches.

所以,你的例子相当于写:

So, your example is equivalent to writing:

x match {
   case MyValue1 | MyValue2 => println ("first match")
   case y | z => println ("second match")
}

您可以使用反引号解决此问题:

You can work around this by using backticks:

x match {
   case MyValue1 | MyValue2 => println ("first match")
   case `myValue1` | `myValue2` => println ("second match")
}

这篇关于Scala 模式匹配小写变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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