Wikiii122
Wikiii122

Reputation: 486

Scala variable naming rules with underscore

What are the rules to name methods and variables in Scala, especially when mixing symbols and letters using _? For instance, why _a_, a_+, __a, __a__a__a__+, ___ are valid names, but _a_+_a or _a_+_ are not?

Upvotes: 0

Views: 768

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

It's in the very first section of the Scala Language Specification:

There are three ways to form an identifier. First, an identifier can start with a letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore ‘_‘ characters and another string composed of either letters and digits or of operator characters.

It's not entirely clear from this, but the operator characters cannot be followed by anything else. Seen here (the pattern for the end of the identifier):

idrest   ::=  {letter | digit} [‘_’ op]

_a_+_a and _a_+_ are illegal because they have another letter or underscore following the operator characters. However, they are legal if you surround them with back quotes.

scala> val `_a_+_` = 1
_a_+_: Int = 1

scala> val `_a_+_a` = 1
_a_+_a: Int = 1

Upvotes: 4

ale64bit
ale64bit

Reputation: 6242

From here:

There are three ways to form an identifier. First, an identifier can start with a letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore ‘_‘ characters and another string composed of either letters and digits or of operator characters. Second, an identifier can start with an operator character followed by an arbitrary sequence of operator characters. The preceding two forms are called plain identifiers. Finally, an identifier may also be formed by an arbitrary string between back-quotes (host systems may impose some restrictions on which strings are legal for identifiers). The identifier then is composed of all characters excluding the backquotes themselves.

You can also see in the link the grammar of the language.

Upvotes: 2

Related Questions