Another type of variable that exists in Kotlin is the immutable variable. The term, immutable, signifies a variable whose value cannot mutate or change after its initialization.
Immutable variables are denoted by the
val keyword and are often referred to as constants in some languages. Here’s how they’re declared in Kotlin:
val variableName: Type = value
Let’s see an example. The following variable contains the value of the Golden Ratio:
val goldenRatio: Double = 1.618
Since we know this value stays constant, its best to declare it with the
val keyword as opposed to
var as we don’t intend on changing it. Although a declaration with
var would have also been accepted by the compiler, the preferred strategy is to declare variables with
var only if we’re certain the value will change somewhere throughout the program, otherwise always use
Let’s see what happens when we try to reassign
goldenRatio to another value:
goldenRatio = 3.2
The above line of code would result in the following error in the terminal stating that reassignment is not allowed:
Pi.kt:5:3: error: val cannot be reassigned goldenRatio = 3.2 ^
In Pi.kt, declare an immutable variable,
- It must have a type of
- It must hold the value,
Note: Since we haven’t utilized this variable and only declared it, you’ll see a Warning message thrown by the compiler stating that the variable hasn’t been used. A Warning is different from an Error and doesn’t prevent execution of your program. Feel free to disregard this for now; it is just Kotlin’s way of ensuring that we don’t have any unused code in our programs.
On the following line, type the variable name and reassign it a different
Double value. Observe the error in the terminal.