Using List
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:
Press + to interact
val fruits: List<String> = listOf("Apple", "Banana", "Grape")println(fruits) //[Apple, Banana, Grape]
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
...