6

Why this fails to compile:

scala> val a? = true
<console>:1: error: illegal start of simple pattern
   val a? = true
          ^

and this works?

scala>  val a_? = true
a_?: Boolean = true
Rogach
  • 26,050
  • 21
  • 93
  • 172

2 Answers2

6

According to the Scala language specification (looking at 2.8, doubt things have changed much since):

idrest ::= {letter | digit} [`_' op]

That is, an identifier can start with a letter or a digit followed by an underscore character, and further operator characters. That makes identifiers such as foo_!@! valid identifiers. Also, note that identifiers may also contain a string of operator characters alone. Consider the following REPL session:

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_16).

scala> val +aff = true
<console>:1: error: illegal start of simple pattern
val +aff = true
^

scala> val ??? = true
???: Boolean = true

scala> val foo_!@! = true
foo_!@!: Boolean = true

scala> val %^@%@ = true
%^@%@: Boolean = true

scala> val ^&*!%@ = 42
^&*!%@: Int = 42

Hope this answers your question.

S.R.I
  • 1,860
  • 14
  • 31
2

Scala's grammar for identifiers is defined in such a way. ? is defined to be an operator character. And an identifier must obey the following rules: it must be a lower-case letter which may be followed by an element of an 'idrest' syntactic category, which is defined as 'letters or digits, possibly followed by _ and an op char.' See Scala Language Specification for more details.

S. Kucherenko
  • 585
  • 3
  • 8