Scala

13 / 53

Scala - Variables and Type Inference




Not able to play video? Try with youtube

Variables are nothing but reserved memory locations to store values. This means that when we create a variable, the compiler allocates a memory based on its data type.

There are two types of variables in Scala - Mutable and Immutable. Mutable variables are defined using var keyword and their value can be changed. Immutable variables are defined using val keyword and their value can not be changed once assigned. You can think of Immutable variables as final variables in Java

Let's do a hands-on on variables. Login to CloudxLab and type scala to launch the scala shell.

Let's define an immutable variable x of integer type with value 8. Type val x: Int = 8. Now try changing the value of x to 9. We have got an error. As discussed we can not change the value of an immutable variable.

Let's define a mutable variable "y" of integer type with value 7. Type var y: Int = 7. Now try changing the value of "y" to 9. We can see that its value is now 9.

Let's understand why do we need immutable variables?

In large systems, we do not want to be in a situation where a variable's value changes unexpectedly as this may lead to unpredictable results.

In the case of Threads, APIs, functions, and classes, we may not want some of the variables to change.

In these scenarios, we define the variables as immutable variables.

In scala, we can define the variables without specifying their datatype. The scala compiler can understand the type of the variable based on the value assigned to it. This is called variable type inference.

Let's do a hands-on on type inference

Let us define a variable x and assign it a value "hi". Type var x = "hi" in the scala shell. As we can see, scala has determined the type of variable x as "String".

Let us explicitly define the type of variable x as a string. Type var x:String = "hi". We can see that variable x is a string.

We should always try to explicitly define a type of variable to ensure that the code is compiled faster and to avoid any unpredictable results.


Loading comments...