Lists are one of the most fundamental and versatile data structures in Kotlin. They allow you to store and manipulate collections of elements in a specific order. Kotlin provides two types of lists: immutable (List
) and mutable (MutableList
).
You can create lists in Kotlin using several methods:
val fruits = listOf("apple", "banana", "orange")
val numbers = listOf(1, 2, 3, 4, 5)
val mutableFruits = mutableListOf("apple", "banana", "orange")
val emptyList = mutableListOf<String>()
Kotlin provides several ways to access list elements:
val fruits = listOf("apple", "banana", "orange")
println(fruits[0]) // Output: apple
println(fruits.first()) // Output: apple
println(fruits.last()) // Output: orange
val mutableFruits = mutableListOf("apple", "banana")
mutableFruits.add("orange")
mutableFruits.addAll(listOf("grape", "kiwi"))
val mutableNumbers = mutableListOf(1, 2, 3, 4, 5)
mutableNumbers.remove(3)
mutableNumbers.removeAt(0)
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
val doubledNumbers = numbers.map { it * 2 }
Kotlin lists come with various useful properties and functions:
size
: Returns the number of elements in the listisEmpty()
: Checks if the list is emptycontains(element)
: Checks if the list contains a specific elementindexOf(element)
: Returns the index of the first occurrence of an elementYou can iterate over lists using various constructs:
val fruits = listOf("apple", "banana", "orange")
// Using a for loop
for (fruit in fruits) {
println(fruit)
}
// Using forEach
fruits.forEach { println(it) }
// Using forEachIndexed
fruits.forEachIndexed { index, fruit ->
println("$index: $fruit")
}
Understanding the difference between List
and MutableList
is crucial:
List
is read-only and cannot be modified after creationMutableList
allows modification (adding, removing, or updating elements)Choose the appropriate type based on your needs and to ensure proper encapsulation in your code.
To further enhance your understanding of Kotlin collections, explore these related topics:
By mastering Kotlin lists, you'll have a powerful tool at your disposal for managing collections of data in your Kotlin projects.