In Kotlin, the terms “mutable” and “immutable” apply not only to variables but also to collections. Much like an immutable variable representing a read-only value, an immutable list contains items that must never be altered. Its syntax is as follows:
var/val listName = listOf(value1, value2, value3)
varin your declaration as well as a descriptive list name.
listOf. This indicates an immutable list.
Note: Once initialized as a
List<String>, the list can only hold String values.
Keeping the above syntax in mind, let’s create an immutable list of String values that represent the countries we’ve visited:
var countriesVisited = listOf("Japan", "Colombia", "Kenya", "Jordan")
countriesVisited was declared a mutable variable with the
var keyword, we can reassign the value of
countriesVisited to store a different list if we’d like. However, since the list was declared immutable with
listOf, the contents of the list cannot change. They must always remain
println(countriesVisited) // Prints: [Japan, Colombia, Kenya, Jordan]
Lastly, when printed to the screen, the list is contained within square brackets as opposed to parentheses.
We’ve learned a handful of rules and new concepts in this exercise. Don’t get discouraged if it doesn’t all stick right away; we’ll be getting ample practice throughout this lesson. Keep going, and let’s create your first Kotlin list! 📝
In Sports.kt, create an immutable list containing the following water sports:
Store this list in a variable,
Output the value of
waterSports on the following line using a print statement.