A collection groups multiple values so code can iterate over them, test membership, and apply operations without manual element-by-element loops. Kotlin supplies familiar List, Set, and Map forms, plus standard-library functions that make common data work concise. section 6.3 section 9.3 section 3.1
Create and use collections
```kotlin val names = listOf("Ada", "Lin", "Mina") val scores = setOf(8, 13, 21) val labels = mapOf(1 to "one", 2 to "two") println(names.last()) println(scores.sum()) println(labels[1]) ``` `listOf`, `setOf`, and `mapOf` create the common collection shapes. Kotlin adds convenient operations such as `last` and `sum` to the standard Java collection classes. section 3.1
Kotlin separates reading a collection from modifying it. `Collection<T>` supports iteration, size, and containment checks but not adding or removing elements. `MutableCollection<T>` extends it with modification operations. Prefer read-only interface types; use mutable types only where mutation is required. A read-only type prevents mutation through that reference, but it does not guarantee that the underlying object cannot change elsewhere. section 8.2.2
Make mutation explicit
```kotlin fun <T> copyElements(source: Collection<T>, target: MutableCollection<T>) { for (item in source) target.add(item) } val source: Collection<Int> = arrayListOf(3, 5, 7) val target: MutableCollection<Int> = arrayListOf(1) copyElements(source, target) // [1, 3, 5, 7] ``` The types document the contract: the function reads `source` and changes `target`. When passing internal state to code that requires a mutable collection, consider a defensive copy. section 8.2.2
Use collection operations to express the result you need:
- Filter matching elements with `filter`, and transform elements with `map`. section 6.3
- Combine elements into one value with `reduce` or `fold`, or organize values with `associate` and `groupBy`. section 6.3
- Check collection-wide conditions with Boolean predicates such as `all`, `any`, and `none`. section 6.3
- Use sequences when chaining operations lazily avoids intermediate collections. section 6.0
Kotlin collections are deeply compatible with Java collections: they use the corresponding Java interfaces and standard classes, so calls across Kotlin and Java need no wrappers or conversions. Kotlin presents read-only and mutable interface variants, while Java-facing mutable operations can still change an object referenced through a Kotlin read-only type. section 8.2.3 section 1.4.4
Figure 8.5 The Collections interface is read-only. MutableCollection extends it and adds methods to modify a collection’s contents.
Compare the read-only `Collection` interface with `MutableCollection`, which adds operations that change contents. section 8.2.2















