Start Coding

Topics

Kotlin Lists

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).

Creating Lists

You can create lists in Kotlin using several methods:

Immutable Lists


val fruits = listOf("apple", "banana", "orange")
val numbers = listOf(1, 2, 3, 4, 5)
    

Mutable Lists


val mutableFruits = mutableListOf("apple", "banana", "orange")
val emptyList = mutableListOf<String>()
    

Accessing Elements

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
    

Common List Operations

Adding Elements (Mutable Lists)


val mutableFruits = mutableListOf("apple", "banana")
mutableFruits.add("orange")
mutableFruits.addAll(listOf("grape", "kiwi"))
    

Removing Elements (Mutable Lists)


val mutableNumbers = mutableListOf(1, 2, 3, 4, 5)
mutableNumbers.remove(3)
mutableNumbers.removeAt(0)
    

Filtering and Transforming


val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
val doubledNumbers = numbers.map { it * 2 }
    

List Properties and Functions

Kotlin lists come with various useful properties and functions:

  • size: Returns the number of elements in the list
  • isEmpty(): Checks if the list is empty
  • contains(element): Checks if the list contains a specific element
  • indexOf(element): Returns the index of the first occurrence of an element

Iterating Over Lists

You 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")
}
    

List vs MutableList

Understanding the difference between List and MutableList is crucial:

  • List is read-only and cannot be modified after creation
  • MutableList allows modification (adding, removing, or updating elements)

Choose the appropriate type based on your needs and to ensure proper encapsulation in your code.

Related Concepts

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.