Why does List in Kotlin not have add and remove methods, and Map does not have put?
Hi everyone! I just started learning Kotlin, coming from Java, and encountered a confusing situation. In Java, we are used to working with ArrayList, HashMap and freely calling list.add(), map.put(), etc. But in Kotlin, when I write:
```kotlin
val myList = listOf(1, 2, 3)
myList.add(4) // Error: Unresolved reference: add
val myMap = mapOf("a" to 1, "b" to 2)
myMap.put("c", 3) // Error: Unresolved reference: put
```
The compiler complains that such methods don't exist. I tried using mutableListOf and mutableMapOf — there add and put work. But why don't regular listOf and mapOf have them? Is this a language bug? Or am I misunderstanding Kotlin's philosophy?
Please tell me how to properly work with collections in Kotlin when I need to both add elements and just read data? And what is the difference between mutable and immutable collections in Kotlin?
No answers yet.
Log in to leave an answer