2

In Scala, I have heard that an identifier is 'stable' if it starts with a capital letter or is surrounded with backticks. What does it mean for an identifier to be stable in Scala? What side effects does this have? Finally, is this related to the convention that constants (like static final in Java) are recommended to start with a capital letter?

Llew Vallis
  • 337
  • 4
  • 12

2 Answers2

5

According to the language reference:

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

Backticks are not directly related to this term. Backticks are needed to wrap something that is not by itself a lexically valid identifier, such as keywords.

You are probably thinking of a 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.

What this talks about is what happens if you use a "normal" lower case variable name in a match pattern expression. The consequence is that the match will always succeed and bind the result to the new binding (that potentially shadows the binding you meant to use).

To get the match to use the existing variable binding you can use backticks/backquotes.

None of this is really related to the Java convention related to naming of constants. That is just a convention.

esl
  • 245
  • 1
  • 9
3

An example of any string matching with an unstable identifier, (Consequence of unstable identifier)

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

executes first case lowPriority, but supposed to print second case. This is because case lowPriority creates a variable lowPriority which matches to anything.

1) Adding backtick(shadowing) to identifier lowPriority makes compare to exact value of existing identifier lowPriority, which is what you want.

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

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

2) Or also uppercasing the identifier fixes the problem.

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

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

prints HighPriority

related links

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?

prayagupa
  • 30,204
  • 14
  • 155
  • 192