In this shot, we’ll learn about the concept of mutable and immutable variables in Scala.
Variables are storage locations that hold values of different data types, such as integers, strings, or booleans. Variables in Scala are of two types:
Mutable means something is changeable after its creation; whereas, immutable means
Scala has particular keywords, var
and val
, to distinguish between mutable and immutable variables.
var
keywordWe can define mutable variables with the var
keyword.
To define a mutable variable without declaring its data type, we write the following code statement:
var mutable_var = "Hello World"
var mutable_var = 70
If we want to specify the data type of mutable variables, we follow the syntax below:
var mutable_var: String = "This is a mutable variable"
var mutable_var: Int = 70
val
keywordWe can define immutable variables with the val
keyword.
To define an immutable variable without declaring its data type, we write the following code statement:
val immutable_var = "This is an immutable variable"
val immutable_var = 70
If we want to specify the data type of immutable variables, we follow the syntax below:
val immutable_var: String = "Hello World"
val immutable_var: Int = 70
Free Resources