Open In App

Scala Identifiers

In programming languages, Identifiers are used for identification purpose. In Scala, an identifier can be a class name, method name, variable name or an object name. 
For example :  

class GFG{
    var a: Int = 20
}
object Main {
    def main(args: Array[String]) {
        var ob = new GFG();
    }
}

In the above program we have 6 identifiers: 



Rules for defining Java Scala

There are certain rules for defining a valid Scala identifier. These rules must be followed, otherwise we get a compile-time error.  

Example: 






// Scala program to demonstrate
// Identifiers
 
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
    // Valid Identifiers
    var `name` = "Siya";
    var _age = 20;
    var Branch = "Computer Science";
    println("Name:" +`name`);
    println("Age:" +_age);
    println("Branch:" +Branch);
    }
}

Output:  

Name:Siya
Age:20
Branch:Computer Science

In the above example, valid identifiers are:  

Main, main, args, `name`, _age, Branch, +

and keywords are: 

Object, def, var, println

 

Types of Scala identifiers

Scala supports four types of identifiers: 

 _GFG, geeks123, _1_Gee_23, Geeks

Example of Invalid alphanumeric identifiers: 

123G, $Geeks, -geeks

Example: 




// Scala program to demonstrate
// Alphanumeric Identifiers
 
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
    // main, _name1, and Tuto_rial are
    // valid alphanumeric identifiers
    var _name1: String = "GeeksforGeeks"
    var Tuto_rial: String = "Scala"
     
    println(_name1);
    println(Tuto_rial);
    }
}

Output: 

GeeksforGeeks
Scala
 +, ++ 

Example: 




// Scala program to demonstrate
// Operator Identifiers
 
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
    // main, x, y, and sum are valid
    // alphanumeric identifiers
    var x:Int = 20;
    var y:Int = 10;
     
    // Here, + is a operator identifier
    // which is used to add two values
    var sum = x + y;
    println("Display the result of + identifier:");
    println(sum);
    }
}

Output: 

Display the result of + identifier:
30
 unary_+, sum_= 

Example: 




// Scala program to demonstrate
// Mixed Identifiers
 
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
    // num_+ is a valid mixed identifier
    var num_+ = 20;
    println("Display the result of mixed identifier:");
    println(num_+);
    }
}

Output: 

Display the result of mixed identifier:
20
`Geeks`, `name` 

Example: 




// Scala program to demonstrate
// Literal Identifiers
 
object Main
{
     
    // Main method
    def main(args: Array[String])
    {
         
    // `name` and `age` are valid literal identifiers
    var `name` = "Siya"
    var `age` = 20
    println("Name:" +`name`);
    println("Age:" +`age`);
    }
}

Output: 

Name:Siya
Age:20

Article Tags :