Read-Only vs Mutable Variables
Learn the fundamental principle of read-only and mutable variables, plus how and when to use them in Kotlin.
We'll cover the following
var number = 17println("number = $number")number = 42 // var can be reassignedprintln("number = $number")
val number = 17println("number = $number")number = 42 // Not allowed, throws an exception
Read-only means that the variable cannot be reassigned once initialized.
You should prefer read-only variables to mutable ones whenever possible, i.e., whenever you don’t have to change the value after initialization.
varto simplify data flow and facilitate reasoning about your code.
Readonly and Mutable Variables
Which of the following code snippets correctly initialize readonly variables? You can select multiple answers.
val a = "Just"
var b = "starting"
val c = "out"
string d = "with Kotlin"
// Create your variables
Kotlin differentiates between read-only and mutable variables at declaration time, forcing you to think about the mutability of state from the start.
vallets you declare read-only variables.
varlets you declare mutable variables.
- Good practice is to prefer
varwhenever possible to reduce mutability and therefore facilitate understanding of the program’s state and data flow.
In the next lesson, you will learn about Kotlin’s fundamental data types and how to use them.