Kotlin Variables: Mutable vs Immutable

In Kotlin, there are two types of variables; mutable variable and immutable variable.

Mutable Variables

  1. Mutable variable is a variable whose value can be changed or updated from time to time.
  2. To declare a mutable variable, we use the var keyword.

3. When you run the programs, it will display below messages in the console.

Immutable Variables

  1. Immutable variable is a variable whose value cannot be changed or altered, like constants.
  2. To declare an immutable variable, use the val keyword.

3. You can see here the program contains an error (i.e. compilation error). Study the error message.

4. Update the codes by commenting line 9. Once you no longer have any errors, try to run the program again. The output will look similar to below.