Kotlin Collection Types
Kotlin Collection Types
Kotlin provides a structured set of collection types for managing groups of elements. Collections are divided into two categories: read only collections that expose only access operations and mutable collections that allow modification. This distinction is enforced at the type system level through separate interfaces, which helps developers communicate intent and prevent accidental modification. Understanding the collection hierarchy, mutability semantics, and the difference between read only views and true immutability is a common interview topic. By the end of this lesson, you will be able to:
- Describe the three main collection types:
List,Set, andMap. - Explain the difference between read only and mutable collection interfaces.
- Identify why read only collections do not guarantee true immutability.
- Apply
kotlinx.collections.immutablefor guaranteed immutable collections.
Read Only Collection Types
Kotlin's read only collection interfaces provide access to elements without exposing mutation operations. The three primary types are:
List is an ordered collection where elements are accessed by index. It preserves insertion order and allows duplicates:
val languages = listOf("Kotlin", "Java", "Kotlin")
println(languages[0]) // Output: Kotlin
println(languages.size) // Output: 3
Set is a collection of unique elements. It does not allow duplicates, and the default implementation (LinkedHashSet) preserves insertion order:
val unique = setOf("Kotlin", "Java", "Kotlin")
println(unique) // Output: [Kotlin, Java]
println(unique.size) // Output: 2
Map is a collection of key value pairs where each key is unique. It provides lookup by key in constant time for the default LinkedHashMap implementation:
val config = mapOf("language" to "Kotlin", "platform" to "Android")
println(config["language"]) // Output: Kotlin
These types are declared through the List<T>, Set<T>, and Map<K, V> interfaces, which do not include any mutation methods like add(), remove(), or put().
Mutable Collection Types
Mutable collections extend the read only interfaces and add modification operations. MutableList extends List, MutableSet extends Set, and MutableMap extends Map:
val names = mutableListOf("Alice", "Bob")
names.add("Charlie")
names.removeAt(0)
println(names) // Output: [Bob, Charlie]
val tags = mutableSetOf("android", "kotlin")
tags.add("compose")
println(tags) // Output: [android, kotlin, compose]
val settings = mutableMapOf("theme" to "dark")
settings["language"] = "en"
println(settings) // Output: {theme=dark, language=en}
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor