
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
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.