List Basics
In this page:
Creating a List
listOf(...) builds a read-only List containing the given elements in the given order, which is the most common way to work with a fixed collection of values.
Example: Creating a List
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println(fruits)
}
Login to try C/C++/Java/PHP code in the editor
Accessing Elements by Index
Elements are retrieved using square brackets with a zero-based index, such as fruits[0] for the first element.
Example: Accessing Elements by Index
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println("First: ${fruits[0]}")
println("Last: ${fruits[fruits.size - 1]}")
}
Login to try C/C++/Java/PHP code in the editor
Common List Properties and Functions
List provides convenient read-only members like .size, .first(), .last(), .isEmpty(), and .contains(item) for inspecting the collection without mutating it.
Example: Common List Properties and Functions
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println("Size: ${fruits.size}")
println("First: ${fruits.first()}")
println("Contains banana: ${fruits.contains("banana")}")
}
Login to try C/C++/Java/PHP code in the editor
Lists Are Read-Only, Not Necessarily Immutable
A List reference cannot itself add or remove elements, but if it points to the same object as a MutableList reference elsewhere, changes made through that other reference are still visible.
Note: This is why List is called read-only rather than immutable in Kotlin's terminology.
Example: Lists Are Read-Only, Not Necessarily Immutable
fun main() {
val mutable = mutableListOf("a", "b")
val readOnlyView: List<String> = mutable
mutable.add("c")
println(readOnlyView)
}
Login to try C/C++/Java/PHP code in the editor
- Trying to call
.add()on aListcreated withlistOf(), forgetting it is read-only and not necessarily mutable. - Assuming a read-only
Listcan never change; if its underlying value is aMutableList, changes made through that reference are still visible through the read-only view. - Using index-based access without checking bounds, causing an
IndexOutOfBoundsExceptionon an invalid index.
listOf(...)creates a read-onlyList-- you cannot add, remove, or replace elements through it.- Elements are accessed by zero-based index using
list[index]orlist.get(index). Listprovides many read-only helper functions like.size,.first(),.last(), and.contains().- A read-only
Listtype does not guarantee true immutability if another reference to the same underlying collection is mutable.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: