Thursday, 20 October 2016

Basics of Scala : Defining a Names in Scala : Day 2 Learnings

Scala names can use letters, numbers, and a range of special operator characters. This makes it possible to use standard mathematical operators (e.g., * and :+ ) and constants (e.g., π and φ ) in place of longer names to make the code more expressive.

The Scala Language Specification defines these operator characters as “all other characters in \u0020-007F and Unicode categories Sm [Symbol/Math] ... except parentheses ([]) and periods.” Square brackets (referred to in the text as parentheses) are reserved for use in type parameterization, while periods are reserved for access to the fields and methods of objects (instantiated types).

Here are the rules for combining letters, numbers, and characters into valid identifiers in Scala:
1. A letter followed by zero or more letters and digits.
2. A letter followed by zero or more letters and digits, then an underscore ( _ ), and then one or more of either letters and digits or operator characters.
3. One or more operator characters.
4. One or more of any character except a backquote, all enclosed in a pair of backquotes

Note: Names enclosed in backquotes can, unlike the other names, be reserved keywords in Scala such as true , while , = , and var .

Let’s try out some of these naming rules in the REPL:

  1. scala> val π = 3.14159
  2. π: Double = 3.14159
The special character “π” is a valid Scala identifier.

  1. scala> val $ = "USD currency symbol"
  2. $: String = USD currency symbol

  1. scala> val o_O = "Hmm"
  2. o_O: String = Hmm

  1. scala> val 50cent = "$0.50"
  2. <console>:1: error: Invalid literal number
  3. val 50cent = "$0.50"
  4.       ^
The value name “50cent” is invalid because names cannot start with numbers. In this case the compiler started parsing the name as a literal number and ran into problems at the letter “c”.

  1. scala> val a.b = 25
  2. <console>:7: error: not found: value a
  3. val a.b = 25
The value name “a.b” is invalid because a period isn’t an operator character.

  1. scala> val `a.b` = 4
  2. a.b: Int = 4
Rewriting this value with backquotes fixes the problem, although the aesthetics of using backquotes isn’t that great.

Value and variable names, by convention, should start with a lowercase letter and then capitalize additional words. This is popularly known as camel case, and though not required it is recommended for all Scala developers. This helps to distinguish them from types and classes which (also by convention, not by rule) follow camel case but start with an uppercase letter.

Share this article with your friends.
Related Posts Plugin for WordPress, Blogger...