2
votes

this works as expected

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

why does this fail?

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 }

'$' is supposed to be a valid identifier character, as demonstrated here:

scala> var y = 1
y: Int = 1

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

Thanks

4
I'm writing a Domain Specific Language for compiling PHP Scripts using Scala.Alex R
I think it because '$' is reserve for the compiler.Eastsun
Why do the variables of your input language need to show up in your compiler implementation? If you're translating to Scala code, you should mangle identifiers in general and specifically avoid the $.Randall Schulz
I want to preserve the "feel" of PHP, and also avoid name collisions without mangling the identifiersAlex R
Again, I don't understand. You're translating PHP to Scala. Who cares what the Scala looks like? And what does it even mean to preserve PHP "feel" in Scala??Randall Schulz

4 Answers

15
votes

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

"The ‘$’ character is reserved for compiler-synthesized identifiers. User programs should not define identifiers which contain ‘$’ characters."

So this non-bug is a formal part of the language specification.

7
votes

Even though it's discouraged, $'s can be written in identifiers. But an identifier starting with a $ does not count as a variable identifier -- only identifiers starting with lower-case letters do. On the other hand a typed pattern id : Type requires a variable identifier in front of the :. That's why the match is rejected.

4
votes

Though legal in identifiers, $ is reserved for use by the compiler. You'll see a lot of $ usage if you call Scala code from Java, for instance.

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

4
votes

Actually, while all other answers are correct in some sense, the explanation here is simpler. A dollar sign is considered an uppercase letter according to the specification and, thus, is treated like a constant in a pattern match.