Scala – Variables

In this tutorial, we will learn about scala variables. Variable is a name declared in programming which reserves memory location to store a value.Based on data types, memory is allocated to a variable by compiler.

In scala, variables can be categorised as mutable and immutable variable, which we will see in details below.

Mutable Variable:

It is a variable whose value can be changed. These variables are declared by using keyword var.

As an example, we have declared a variable named gender by using keyword var and assigned the value as ‘male’. Now, if we want to change value of variable gender from ‘male’ to ‘female; , it is possible and that’s why it is called Mutable Variable.

scala> var gender : String = "male"
gender: String = male
scala> gender = "female"
gender: String = female

In the above example, data type is defined after variable name separated by a colon(:).

Immutable Variable:

When a variable is declared with a keyword val, its value can not be changed and it will throw an error if we try to change its value. These variables are called Immutable Variable.

Let’s take the above example, and declare the variable named gender by using keyword val and assigned the value as ‘male’. Now, if we want to change value of variable gender from ‘male’ to ‘female; , it is not possible and it will throw an error.

scala> val gender :String = "male"
gender: String = male

scala> gender = "female"
<console>:12: error: reassignment to val
       gender = "female"

Scala Variables Type Inference:

You have seen above, that when we are writing the data type while declaring the variable. What if we don’t write data type? Will it throw any error?

It will not throw any error, instead compiler infers data type for the variable itself when we assign the initial value to that variable.

scala> var a = 2
a: Int = 2

scala> val b = "Salary"
b: String = Salary

As you can see , in the above example that we have not defined data types explicitly for the variables a and b. But compiler inferred their data types as Int and String respectively from their initial values ‘2’ and ‘Salary’. This is called variable type inference.

Multiple Assignment:

Is it possible to assign multiple variables in one statement?

Answer is YES. It is possible with help of Tuple. A tuple can hold multiple objects of different types and it can be assigned to a val variable. We will learn about tuple more in coming chapters.

scala> val (name :String, age : Int) = Tuple2("John", 30)
name: String = John
age: Int = 30
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...