- Immutable Variables — Immutable variables are also known as read-only variables. They are declared using the val keyword. Once these variables have been declared, we cannot change their values.
The syntax is as follows :
val variableName = value
For example,
val sample = "interview"
sample = "interviewbit" // results in compile time error
The second line in the above code snippet would result in a compile-time error as expected.
Because it can be initialized with the value of a variable, an immutable variable is not a constant. It means that the value of an immutable variable does not need to be known at compile-time and that if it is defined inside a construct that is called several times, it can take on a different value with each function call. For example,
var sample = "interview"
val newSample = sample // no compile time error
The above code snippet runs fine and does not produce any errors.
- Mutable Variables - In a mutable variable, the value of the variable can be changed. We use the keyword “var” to declare such variables.
The syntax is as follows :
var variableName = value
For example,
var sample = "interview"
sample = "fun" // no compile time error
The above code snippet runs fine and does not produce any errors.