Scala - Identifiers



Scala identifiers are the names used for objects, classes, variables, and methods etc. These identifiers are case sensitive and they cannot be Scala keywords. Scala has four types of identifiers: Alphanumeric, Operator, Mixed and Literal.

Consider following Scala program −

class Person(var name: String, var age: Int) {
   def greet(): Unit = {
      println(s"Hello, my name is $name, and I am $age years old.")
   }
}

object Main {
   def main(args: Array[String]): Unit = {
      val person1 = new Person("Alice", 30)

       person1.greet()
   }
}

In the above program, these are various identifiers −

  • Person − Class name
  • person1 − Object name
  • Main − Object name
  • main − Method name
  • args − Variable name

Types of Scala Identifiers

All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers.

1. Alphanumeric Identifiers

These identifiers start with a letter (lowercase or uppercase) or an underscore and followed by digits, letters and underscores. For example, _Name, _name, name123, _1_name_23, name etc. are valid Alphanumeric identifiers. Whereas, 123name, $name, -name etc are invalid identifiers in Scala.

object Main {
   def main(args: Array[String]): Unit = {
      // Valid alphanumeric identifiers
      var myVariable123: Int = 42
      var myLongVariableName: String = "Hello, World!"

      println(myVariable123)
      println(myLongVariableName)
   }
}

2. Operator Identifiers

These identifiers contain one or more operator characters. For example, +, ++, :, ?, ~, # etc are Operator identifiers in Scala. The Scala compiler transforms operator identifiers into Java-compatible identifiers. For example, `:->` becomes `$colon$minus$greater`.

object Main {
   def main(args: Array[String]): Unit = {
      // Valid operator identifiers
      var a: Int = 5
      var b: Int = 3

      // Using operator identifiers (+, -, *, /)
      var sum = a + b
      var difference = a - b
      var product = a * b
      var quotient = a / b

      println("Sum: " + sum)
      println("Difference: " + difference)
      println("Product: " + product)
      println("Quotient: " + quotient)
   }
}

3. Mixed Identifiers

These identifiers contain alphanumeric identifiers followed by underscore and an operator identifier. For example, sum_ =, unary_+, myvar_=, etc are Mixed identifiers in Scala. In this context, "unary_+" defines an unary plus operator. And "myvar_=" defines an assignment operator, which is a form of operator overloading.

object Main {
   def main(args: Array[String]): Unit = {
      // Valid mixed identifier
      var total_$$ = 1000

      println("Total amount: " + total_$$)
   }
}

4. Literal Identifiers

These identifiers contain arbitrary strings enclosed with backticks (`...`). For example, `Name`, `name` etc are Literal identifiers in Scala.

object Main {
   def main(args: Array[String]): Unit = {
      // Valid literal identifiers
      var `product name` = "Laptop"
      var `purchase date` = "2023-10-31"

      println("Product Name: " + `product name`)
      println("Purchase Date: " + `purchase date`)
   }
}

Rules for Defining Scala Identifiers

These are some predefined rules for valid identifiers. These rules must be followed otherwise we get a compilation error.

1. Case-Sensitivity

Scala identifiers are case-sensitive. For example, `myVariable` and `myvariable` are two different variable names. These are not the same.

2. Reserved Keywords

You can not use Scala keywords as identifiers. For example, you can not use `if`, `class`, `object`, `val` etc as identifiers.

3. Special Characters

Scala identifiers can not start with a digit. These identifiers can include letters, digits, underscores(_) and dollar signs ($). It is good practice to avoid using dollar signs as they are typically used by the Scala compiler for code generation and may lead to confusion.

4. Starting with Letter

Scala identifiers should not start with digits ([0-9]). These can start with a letter (uppercase or lowercase) or an underscore. For example "123name" is not a valid Scala identifier.

5. Length

We should define identifiers in between length 4 to 15 characters in length. Extremely long identifiers have less code readability. However, there is no strict limit on the length of an identifier in Scala.

Examples of Scala Identifiers

For example, below table has valid and invalid identifiers in Scala −

Valid Identifiers in Scala Invalid Identifiers in Scala
myVariable my-variable (hyphen not allowed)
name123 123name (can not start with digit)
ClassName if (reserved keyword)
_privateVar $special$ (should be avoided for readability but can be allowed)

Another example,

object IdentifierExample {
   def main(args: Array[String]): Unit = {
    
      // Valid Identifiers
      var identifierWithDigits123 = "Hello, World!"
      var _underscoreIdentifier = "I am valid."
      var camelCaseIdentifier = "CamelCase is allowed."
      val `my identifier` = "Spaces are allowed when enclosed in backticks."

      println(identifierWithDigits123)
      println(_underscoreIdentifier)
      println(camelCaseIdentifier)
      println(`my identifier`)

      // Invalid Identifiers (Will not compile)
      // var 123identifier = "Invalid, starts with a digit."
      // val hyphen-identifier = "Invalid, contains a hyphen."
      // var keywords = "Invalid, using a keyword as an identifier."
      // val identifier with spaces = "Invalid, spaces without backticks."
   }
}

In this program, invalid identifiers are shown as comments. The output will be valid identifier names with their values.

Advertisements