Lists
Prerequisites: for loops and ranges
A list is an ordered collection of values of the same type.
Real-world analogy: a list is a numbered row of lockers. Each locker holds one item, and you find an item by its locker number.
Read-only and mutable lists
Kotlin separates lists you can only read from lists you can change:
val fruits = listOf("apple", "banana", "cherry") // read-only
val basket = mutableListOf("apple") // can change
val empty = mutableListOf<Int>() // empty, type given
Prefer read-only lists; use a mutable one only while you're building or changing the contents.
Reading elements
Positions (indexes) start at 0:
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println(fruits[0])
println(fruits[2])
println(fruits.size)
println(fruits.first())
println(fruits.last())
println(fruits.getOrNull(5))
println(fruits.indexOf("banana"))
println("cherry" in fruits)
}
apple
cherry
3
apple
cherry
null
1
true
getOrNull(5) returns null instead of crashing when the index is out
of range.
Changing a mutable list
fun main() {
val fruits = mutableListOf("apple", "banana")
fruits.add("cherry")
fruits.add(0, "apricot")
fruits[1] = "avocado"
println(fruits)
fruits.remove("banana")
fruits.removeAt(0)
println(fruits)
fruits += listOf("date", "fig")
println(fruits)
}
[apricot, avocado, banana, cherry]
[avocado, cherry]
[avocado, cherry, date, fig]
Note that fruits is a val — the variable always refers to the same
list — yet the list's contents can change. val stops
reassignment, not modification.
Common mistakes
- Reading past the end:
fruits[3]on a 3-element list throwsIndexOutOfBoundsException. UsegetOrNullwhen unsure. - Trying to
addto alistOf(...)list — read-only lists have noaddfunction.
Practice
Create a mutable list of three cities, add a fourth, and print the list, its size, and the last city.
Show solution
fun main() {
val cities = mutableListOf("Lagos", "Lima", "Oslo")
cities.add("Tokyo")
println(cities)
println(cities.size)
println(cities.last())
}
[Lagos, Lima, Oslo, Tokyo]
4
Tokyo