Lists help you keep many items together in order. You use listOf to make a list you cannot change, and mutableListOf to make a list you can change later.
List creation (listOf, mutableListOf) in Kotlin
fun main() { val fixedList = listOf<Type>(item1, item2, item3) val changeableList = mutableListOf<Type>(item1, item2, item3) }
listOf creates a list that cannot be changed (read-only).
mutableListOf creates a list that you can add, remove, or change items in.
val emptyList = listOf<String>()
val singleItemList = listOf(42)
val mutableList = mutableListOf("apple", "banana") mutableList.add("cherry")
val mutableEmptyList = mutableListOf<Int>() mutableEmptyList.add(10)
This program shows how to create a fixed list and a mutable list. It prints the fixed list, then adds and removes items from the mutable list, printing the list each time.
fun main() { // Create a fixed list of fruits val fruits = listOf("apple", "banana", "cherry") println("Fixed list of fruits: $fruits") // Create a mutable list of numbers val numbers = mutableListOf(1, 2, 3) println("Mutable list before adding: $numbers") // Add a number to the mutable list numbers.add(4) println("Mutable list after adding: $numbers") // Remove a number from the mutable list numbers.remove(2) println("Mutable list after removing: $numbers") }
Time complexity: Accessing items by index is fast (O(1)). Adding or removing items in mutableListOf is usually fast but can be slower if the list needs to resize.
Space complexity: Lists use space proportional to the number of items they hold.
A common mistake is trying to add or remove items from a list created with listOf, which is not allowed.
Use listOf when you want a list that should not change, and mutableListOf when you need to change the list after creating it.
listOf creates a fixed, read-only list.
mutableListOf creates a list you can change by adding or removing items.
Choose the right list type based on whether you need to change the list later.