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.

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 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.

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.

Print Friendly, PDF & Email
Scala - Data Types
Scala – OOPs concepts
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

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