Open In App

Variables in Scala

Improve
Improve
Like Article
Like
Save
Share
Report

Variables are simply storage locations. Every variable is known by its name and stores some known and unknown piece of information known as value. So one can define a variable by its data type and name, a data type is responsible for allocating memory for the variable. In Scala there are two types of variables: 

  • Mutable Variables
  • Immutable Variables

Let’s understand each one of these variables in detail. 

Mutable Variable: These variables are those variables that allow us to change a value after the declaration of a variable. Mutable variables are defined by using the var keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. 

Syntax:  

var Variable_name: Data_type = "value";

Example: 

var name: String = "geekforgeeks";

Here, name is the name of the variable, string is the data type of variable and geeksforgeeks is the value that store in the memory. 
Another way of defining variable: 

Syntax: 

var variable_name = value

For Example: 

var value = 40 
//it works without error 
value = 32

 Here, the value is the name of the variable. 

Immutable Variable: 
These variables are those variables that do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the val keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. 

Syntax: 

val Variable_name: Data_type =  "value";

Example: 

val name: String = "geekforgeeks";

Here, a name is the name of the variable, a string is the data type of variable and geeksforgeeks is the value that store in the memory. Another way of defining variable: 

Syntax: 

val variable_name = "value"

For Example: 

val value = 40 
//it will give an error 
value = 32

 Here value is the name of the variable. 

Rules for naming variable in Scala 

  • Variable name should be in lower case.
  • Variable name can contain letter, digit and two special characters(Underscore(_) and Dollar($) sign)
  • Variable name must not contain the keyword or reserved word.
  • Starting letter of the variable name should be an alphabet.
  • White space is not allowed in variable name.

Note: Scala supports multiple assignments but you can use multiple assignments only with immutable variables.

For Example: 

val(name1:Int, name2:String) = (2, "geekforgeeks")

Variable Type Inference In Scala: Scala supports variable type inference. In variable type inference values are directly assigned to the variable without defining its data type, the Scala compiler automatically resolves which value belongs to which data type. 

For Example: 

var name1=40;
val name2="geeksforgeeks";

Here, name1 is by default int type and name2 is by default string type. 


Last Updated : 01 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads