0
0
KotlinHow-ToBeginner · 3 min read

How to Create List in Kotlin: Syntax and Examples

In Kotlin, you create a list using listOf() for an immutable list or mutableListOf() for a mutable list. These functions let you store multiple values in an ordered collection.
📐

Syntax

To create a list in Kotlin, use listOf() for a read-only list or mutableListOf() for a list you can change later. You put the items inside the parentheses separated by commas.

  • listOf(): Creates an immutable list that cannot be changed after creation.
  • mutableListOf(): Creates a mutable list that you can add or remove items from.
kotlin
val immutableList = listOf("apple", "banana", "cherry")
val mutableList = mutableListOf("dog", "cat", "bird")
💻

Example

This example shows how to create both immutable and mutable lists, print their contents, and add an item to the mutable list.

kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println("Immutable list: $fruits")

    val animals = mutableListOf("dog", "cat", "bird")
    println("Mutable list before adding: $animals")
    animals.add("fish")
    println("Mutable list after adding: $animals")
}
Output
Immutable list: [apple, banana, cherry] Mutable list before adding: [dog, cat, bird] Mutable list after adding: [dog, cat, bird, fish]
⚠️

Common Pitfalls

One common mistake is trying to modify an immutable list created with listOf(). This will cause a compile-time error because the list cannot be changed. Always use mutableListOf() if you need to add or remove items.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3)
    // numbers.add(4) // This line will cause an error: Unresolved reference: add

    val mutableNumbers = mutableListOf(1, 2, 3)
    mutableNumbers.add(4) // This works fine
    println(mutableNumbers)
}
Output
[1, 2, 3, 4]
📊

Quick Reference

FunctionDescription
listOf()Creates an immutable (read-only) list
mutableListOf()Creates a mutable list you can change
add()Adds an item to a mutable list
remove()Removes an item from a mutable list

Key Takeaways

Use listOf() to create a list that cannot be changed.
Use mutableListOf() to create a list you can add or remove items from.
Trying to modify an immutable list causes a compile error.
Lists store items in order and can hold any type of data.
Remember to choose the right list type based on whether you need to change it.