List vs MutableList in Kotlin
In Kotlin, List and MutableList are interfaces that represent collections of elements, but they differ in mutability (whether they can be modified after creation).
1. List (Immutable List)
- Read-only (cannot be modified after creation).
- Provides operations to access elements but not to add, remove, or modify them.
- Implemented by
ArrayList, LinkedList, etc., but in an immutable way.
Example:
val immutableList: List<String> = listOf("Apple", "Banana", "Cherry")
// Accessing elements
println(immutableList[0]) // "Apple"
// Trying to modify will cause a compile-time error
// immutableList.add("Date") // ❌ Error: No such method
2. MutableList (Mutable List)
- Modifiable (can add, remove, or update elements).
- Extends
List and adds mutation methods like add(), remove(), set(), etc.
- Implemented by
ArrayList, LinkedList, etc.
Example:
val mutableList: MutableList<String> = mutableListOf("Apple", "Banana", "Cherry")
// Accessing elements
println(mutableList[0]) // "Apple"
// Modifying the list
mutableList.add("Date") // ✅ Works
mutableList.remove("Banana") // ✅ Works
mutableList[0] = "Avocado" // ✅ Works
println(mutableList) // [Avocado, Cherry, Date]
Key Differences
| Feature | List (Immutable) | MutableList (Mutable) |
|---|
| Modifiable? | ❌ No | ✅ Yes |
| Methods | get(), indexOf(), contains(), etc. | All List methods + add(), remove(), set(), etc. |
| Use Case | When data should not change (e.g., constants) | When data needs to be modified (e.g., dynamic collections) |
Conversion Between Them
List → MutableList (Copy to a new mutable list):
val immutableList = listOf("A", "B", "C")
val mutableList = immutableList.toMutableList()
mutableList.add("D") // ✅ Works
MutableList → List (Upcasting, no copy needed):
val mutableList = mutableListOf("A", "B", "C")
val immutableList: List<String> = mutableList
// immutableList.add("D") // ❌ Error (still read-only)
When to Use Which?
- Use
List when you need a read-only collection (e.g., configuration data, constants).
- Use
MutableList when you need to modify the collection (e.g., dynamic data processing).
Would you like examples of common operations on both types? 😊