Read-Only vs. Mutable
Wait! Unlike Java, Kotlin makes a clear distinction between Read-Only (Immutable) and Mutable collections. This is a key safety feature.
- Read-Only: You can read data but not add or remove items. (e.g.,
listOf(),setOf(),mapOf()). - Mutable: You can add, remove, and update items. (e.g.,
mutableListOf(),mutableSetOf()).
kotlin
Creating Collections
| Collection | Read-Only | Mutable |
|---|---|---|
| List | listOf(1, 2) | mutableListOf(1, 2) |
| Set | setOf(1, 1, 2) | mutableSetOf(1, 2) |
| Map | mapOf("A" to 1) | mutableMapOf("A" to 1) |
Collection Transformations
Kotlin provides a rich set of functional operations to transform your data.
kotlin
The it Keyword
In Kotlin, if a lambda has only one parameter, you can refer to it using the shorthand
it.kotlin
Summary
| Term | Description |
|---|---|
| List | Ordered collection of items |
| Set | Unordered collection of unique items |
| Map | Key-Value pairs |
| Mutable | Collection that can be changed |
| filter | Keep items that match a condition |
| map | Transform every item in a list |
| Best For | Organizing and processing data streams |
| Logic | Favor read-only collections whenever possible |
| Safety | Prevents accidental modifications in concurrent code |
| Modern | Functional programming style for data manipulation |
| Standard | Use List<T> as the default collection type |
| Identity | Collections are backed by standard Java collections for performance |