Using List
Explore how to create and manage immutable and mutable lists in Kotlin. Understand list access using index operators, immutability benefits, and how to safely modify collections using Kotlin's built-in functions.
We'll cover the following...
Creating a list in Kotlin
As a first step in creating a list, Kotlin wants you to declare your intent—immutable or mutable. To create an immutable list, use listOf()—immutability is implied, which should also be our preference when there’s a choice. But if you really need to create a mutable list, then use mutableListOf().
The function listOf() returns a reference to an interface kotlin.collections.List<T>. In the following code the reference fruits is of this interface type, specialized to String for the parametric type:
To access an element in the list you may use the traditional get() method, but the index operator [], which routes to the same method, may be used as well.
// lists.kts
println("first's ${fruits[0]}, that's ${fruits.get(0)}")
//first's Apple, that's Apple
The index operator [] is less noisy than get() and is more convenient—use it freely instead of get(). You may check if a value exists in the collection using the contains() method or using the in operator—we’ll dig ...