Kotlin Lists
A list is a collection that holds values in order. A list made with listOf keeps the same values for its whole life.
A whole list printed
The list holds three names in order. Printing it shows the names inside square brackets.
fun main() {
val names = listOf("Ana", "Bo", "Cy")
println(names)
}One value picked by index
Index 1 picks the second value. The output is that one value alone.
fun main() {
val names = listOf("Ana", "Bo", "Cy")
println(names[1])
}A missing index with getOrNull
Index 9 is past the end of the list. getOrNull gives null instead of stopping the program.
fun main() {
val names = listOf("Ana", "Bo", "Cy")
println(names.getOrNull(9))
}Each value printed by a loop
The for loop visits each value in order. Each visit prints one name.
fun main() {
val names = listOf("Ana", "Bo", "Cy")
for (name in names) {
println(name)
}
}Example
fun main() {
val names = listOf("Ana", "Bo", "Cy")
println(names.size)
println(names[0])
println(names.getOrNull(5))
}Key points
- listOf: the call that builds a list from values in order.
- Use a list index in square brackets to pick one value.
- The first index is 0.
- Use getOrNull to ask for an index that may not exist.
- size: the .size value counts the values in a list.
In this example, the list holds three names. The size prints 3. Index 0 prints Ana, and getOrNull for index 5 prints null.
Note
A list from listOf cannot change after it is built.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does listOf("Ana", "Bo", "Cy") print?