Quick Answer

listOf vs mutableListOf

Understanding the Issue

Kotlin distinguishes between immutable (listOf) and mutable (mutableListOf) collections. The listOf function creates a read-only view that may or may not be truly immutable.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Modifying immutable list
val list = listOf(1, 2, 3)
list.add(4) // Error

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution 1: Use mutable list
val mutable = mutableListOf(1, 2, 3)
mutable.add(4)

// Solution 2: Create new list
val newList = list + 4 // Creates new list

Key Takeaways

Choose collection type based on whether you need mutability.