Course Content
Introduction to Scala
Introduction to Scala
Mutable and Immutable Variables/Data Types
As you have seen, previously we created variables using the val
keyword. However, there are, in fact, two types of variables in Scala: mutable and immutable and consequently two key words:var
and val
, respectively.
Immutable Variables
Let's first discuss immutable variables.
If a variable is declared as immutable, it means that its state cannot be modified after initialization. Any attempt to reassign a new value to the variable will result in a compile-time error. In Scala, immutable variables are declared using the val
keyword which means that we have previously dealt only with immutable variables.
Immutable variables are exactly what we need whenever we have to initialize a constant.
Main
val pi = 3.14 // Initializing a constant
As you can see, we have used an immutable variable named pi
for storing a the value of Pi which is a constant and should not be changed.
Mutable Variables
Now, let's proceed to mutable variables.
This means that after you assign an initial value to a mutable variable, you can later change or update that value to something different as needed throughout the scope in which the variable is accessible. In Scala, mutable variables are declared with the var
keyword, and they allow for reassignment.
Let's now take a look at an example:
Main
object Main { def main(args: Array[String]): Unit = { var myAge = 10 println(myAge) myAge = myAge + 1 // Increasing the value of myAge by 1 println(myAge) } }
As you can see, we have successfully added changed the value of the myAge
variable by adding 1 to it, so now its value is 11. If our variable was immutable (val
), we would get an error.
Mutable and Immutable Data Types
Speaking of mutable and immutable data types (or rather their instances, to be precise) in Scala, these concepts have a slightly different meaning.
All of the previously mentioned basic data types are immutable, while Array
is mutable, which we'll discuss later in the course.
With basic data types immutability means the value represented by an instance of the basic data type (e.g instance of Int
) cannot be changed or altered once it is created.
Let's now take a look at an example to make things clear:
Main
object Main { def main(args: Array[String]): Unit = { var number = 20 number = 30 println(number) } }
In this code, number
is initially assigned the value 20
. When we later assign number
to 30
, we're not changing the value 20
into 30
. Instead, number now simply references a different object in computer memory, 30
.
Thanks for your feedback!