Why doesn't scala allow the $$ identifier in a case statement?

this works as expected

scala> 3 match {case x: Int => 2 * x}
res1: Int = 6

why is it failing?

scala> 3 match {case $ x: Int => 2 * $ x}
: 1: error: '=>' expected but ':' found.
       3 match {case $ x: Int => 2 * $ x}
                        ^

scala> 3 match {case `$ x`: Int => 2 * $ x}
: 1: error: '=>' expected but ':' found.
       3 match {case `$ x`: Int => 2 * $ x}
                          ^

scala> 3 match {case `$ x`: Int => 2 * $ x}
: 1: error: '=>' expected but ':' found.
       3 match {case `$ x`: Int => 2 * $ x}

'$' must be a valid identifier character as shown here:

scala> var y = 1
y: Int = 1

scala> var $ y = 2
$ y: Int = 2

thanks

+2


a source to share


4 answers


In fact, while all the other answers are correct in some sense, the explanation is simpler here. The dollar sign is considered an uppercase letter according to the specification and is thus treated as a constant in pattern matching.



+4


a source


From "The Scala Language Specification", Chapter 1 ("Lexical Syntax"):

"The $ character is reserved for compiler-generated identifiers. It must not define identifiers containing" $ characters ".



Thus, this non-bug is an official part of the language specification.

+15


a source


Even though it's discouraged, $ can be written to identifiers. But an identifier that starts with $ is not considered a variable identifier - only identifiers that start with lowercase letters. On the other hand, a typed template identifier: Type requires a variable identifier before :. This is why the match is rejected.

+7


a source


Although legal in identifiers, $

reserved for compiler use. You will see a lot of use $

if you call Scala code from Java for example.

And in order to make it 100% clear, "reserved" means that you can't declare identifiers with it and expect your code to work.

+4


a source







All Articles