Identifiers Characters

来源:互联网 发布:mac terminal 指令 编辑:程序博客网 时间:2024/06/08 11:08

What characters can you use in identifiers?
Here is a summary of the rules for identifiers, used for method and type names, variables, etc:

  1. Characters
    Scala allows all the printable ASCII characters, such as letters, digits, the underscore _ , and the dollar sign $, with the exceptions of the “parenthetical” characters, (, ), [, ], {, and }, and the “delimiter” characters, ’(backticks倒引号) ' " . ; and , . Scala allows the other characters between \u0020 and \u007F that are not in the sets just shown, such as mathematical symbols, the so-called operator characters like / and <, and some other symbols.
  2. Reserved words can’t be used
    As in most languages, you can’t reuse reserved words for identifiers.
    Reserved words lists
  3. Plain identifiers—combinations of letters, digits, $, _, and operators
    A plain identifier can begin with a letter or underscore, followed by more letters, digits, underscores, and dollar signs. Unicode-equivalent characters are also allowed.

    Scala reserves the dollar sign for internal use, so you shouldn’t use it in your own identifiers, although this isn’t prevented by the compiler.

    After an underscore, you can have either letters and digits, or a sequence of operator characters. The underscore is important. It tells the compiler to treat all the characters up to the next whitespace as part of the identifier. For example, val xyz_++= = 1 assigns the variable xyz_++= the value 1, while the expression val xyz++= = 1 won’t compile because the “identifier” could also be interpreted as xyz ++=, which looks like an attempt to append something to xyz. Similarly, if you have operator characters after the underscore, you can’t mix them with letters and digits. This restriction prevents ambiguous expressions like this: abc_-123. Is that an identifier abc_-123 or an attempt to subtract 123 from abc_?

  4. Plain identifiers—operators
    If an identifier begins with an operator character, the rest of the characters must be operator characters.
  5. “Back-quote” literals
    An identifier can also be an arbitrary string between two back quote characters, e.g.,

    def `test that addition works` = assert(1 + 1 == 2). 
  6. Pattern-matching identifiers
    In pattern-matching expressions , tokens that begin with a lowercase letter are parsed as variable identifiers, while tokens that begin with an uppercase letter are parsed as constant identifiers (such as class names). This restriction prevents some ambiguities because of the very succinct variable syntax that is used, e.g., no val keyword is present.


Ref

《Programming Scala》

0 0