Learn
Lists
Creating an Immutable List

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) 
  • For a list to be used and referenced throughout a program, it must be stored in a variable. Make sure to use keywords val or var in your declaration as well as a descriptive list name.
  • The creation of the Kotlin list begins on the right side of the assignment operator with the term, listOf. This indicates an immutable list.
  • The term is then followed by a pair of parentheses that holds a collection of elements separated by commas.
  • Like variable declarations, the type of list can be inferred by the compiler or declared by the user. For example, a list of String values would be referenced as a List<String>.

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")

Since 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 "Japan", "Colombia", "Kenya", and "Jordan".

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! 📝

Instructions

1.

In Sports.kt, create an immutable list containing the following water sports:

  • "Wind Surfing"
  • "Sailing"
  • "Swimming"
  • "Jet Skiing"
  • "Water Skiing"

Store this list in a variable, waterSports.

2.

Output the value of waterSports on the following line using a print statement.

Folder Icon

Take this course for free

Already have an account?