Scala Identifiers Example Tutorial

Filed Under: Scala

The names of variables, classes, objects and methods are collectively called Identifiers. Scala identifiers are case sensitive. We have been using identifiers all through the tutorial series. Let us now see them in more detail.

Scala Identifiers Types

  1. AlphaNumeric Identifiers
  2. Alphanumeric identifiers start with a letter or underscore that can be further followed by digits, letters or underscores. The $ character is reserved keyword and cannot be used as identifiers.

    For example sage,sname,_id etc.. are valid identifiers.

    $age, -id, 45name are invalid identifiers.

    
    object alphanumeric {
    def main(args:Array[String]) {
    
    	val  sage = 8 ;
    	val sname = "Rob";
        
    	println("Age :"+sage)
    	println("Name:"+sname)
    }
    }
    

    When executed main method, it produces below output.

    
    Age :8
    Name:Rob
    

    Here the variables sage and sname are legal identifiers of Integer and String data types.

  3. Operator identifiers
  4. An operator consists of one or more operator characters. Operator characters include +, :, ?, ~ or # .

    For example + , – , => :::

    
    object Operator {
    def main(args:Array[String]) {
    	val a =10 ;
    	val b=42;
        
    	val c = a + b ;
    	val d = b -a ;
       
        
    println("Result of + operator identifier: "+c);
    println("Result of - identifier: "+d);
    
    }
    }
    

    Output:

    
    Result of + operator identifier: 52
    Result of - identifier: 32
    

    In the above example +, – are the operator identifiers which adds and subtracts the variables and prints the result.

  5. Mixed Identifiers
  6. A mixed identifier contains alphanumeric character followed by underscore and an operator identifier.

    Example unary_+ , myVar_=

    
    object Mixed {
    	def main(args:Array[String]) {
        	val marks_+ = 50;
        	println(marks_+);
    	}
    }
    

    Output:
    50

    In the above example marks_+ is a mixed identifier.

  7. Literal identifiers
  8. A literal identifier is an arbitrary string enclosed with back ticks (`……`) .

    For example; `age` `name` etc are literal identifiers

    
    object Literal {
    	def main(args:Array[String]) {
    	val `x` = 10;
    	val `message` = "Hello"
    	println(`x` + "\n" + `message`);
        
    }
    }
    

    Output:
    10
    Hello

    Here the variables x and message are enclosed with back ticks indicating the literal identifiers.

That’s all for a quick roundup on Scala identifiers, we will look into regular expressions in scala in next tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages