在 Scala 中使用稳定标识符的后果是什么?

What are the Consequences of Using a Stable Identifier in Scala?

在 Scala 中,我听说如果标识符以大写字母开头或被反引号包围,则标识符为 'stable'。标识符在 Scala 中保持稳定意味着什么?这有什么副作用?最后,这是否与建议常量(如Java中的static final)以大写字母开头的约定有关?

根据语言reference:

A stable identifier is a path which ends in an identifier.

反引号与该术语没有直接关系。需要反引号来包装本身不是 lexically 有效标识符的内容,例如关键字。

你可能在想 stable identifier pattern:

To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter. However, it is possible to enclose such a variable name in backquotes; then it is treated as a stable identifier pattern.

这里讨论的是如果您在匹配模式表达式中使用 "normal" 小写变量名称会发生​​什么。结果是匹配将始终成功并将结果绑定到 new 绑定(这可能会隐藏您打算使用的绑定)。

要匹配以使用现有的变量绑定,您可以使用 backticks/backquotes。

None 这实际上与常量命名相关的 Java 约定有关。那只是一个惯例。

任何字符串与不稳定标识符匹配的示例,(不稳定标识符的后果

val highPriority = "High"
val lowPriority = "Low"

"i dont match lowPriority, but this pattern matches to first case" match {
  case lowPriority => println("lowPriority")
  case _ => println("highPriority")
}

执行第一种情况 lowPriority,但应该打印第二种情况。这是因为 case lowPriority 创建了一个匹配任何内容的变量 lowPriority

1) 向标识符 lowPriority 添加反引号(遮蔽)使得与现有标识符低优先级的精确值进行比较,这正是您想要的。

val highPriority = "High"
val lowPriority = "Low"

"i dont match lowPriority" match {
  case `lowPriority` => println("LowPriority")
  case _ => println("HighPriority")
}

2) 或者将标识符大写也可以解决问题。

val HighPriority = "High"
val LowPriority = "Low"

"i dont match LowPriority, prints second case" match {
  case LowPriority => println("LowPriority")
  case _ => println("HighPriority")
}

打印HighPriority

相关链接

https://www.scala-lang.org/files/archive/spec/2.11/03-types.html#paths

Why can't a variable be a stable identifier?

In scala pattern matching, what is suspicious shadowing by a variable pattern?

Why does pattern matching in Scala not work with variables?