Mobile Development Kotlin Subjective
Oct 04, 2025

Explain Kotlin collections and the difference between mutable and immutable collections.

Detailed Explanation
Kotlin distinguishes between mutable and immutable collections at the type level.\n\n**Immutable collections (read-only):**\n\nval list: List = listOf("a", "b", "c")\nval set: Set = setOf(1, 2, 3)\nval map: Map = mapOf("a" to 1, "b" to 2)\n\n// list.add("d") // Compilation error\n\n\n**Mutable collections:**\n\nval mutableList: MutableList = mutableListOf("a", "b")\nval mutableSet: MutableSet = mutableSetOf(1, 2)\nval mutableMap: MutableMap = mutableMapOf("a" to 1)\n\nmutableList.add("c") // OK\nmutableSet.remove(1) // OK\nmutableMap["b"] = 2 // OK\n\n\n**Collection operations:**\n\nval numbers = listOf(1, 2, 3, 4, 5)\n\n// Transformations (return new collections)\nval doubled = numbers.map { it * 2 }\nval filtered = numbers.filter { it > 2 }\nval sorted = numbers.sortedDescending()\n\n// Aggregations\nval sum = numbers.sum()\nval max = numbers.maxOrNull()\nval any = numbers.any { it > 3 }\nval all = numbers.all { it > 0 }\n\n// Grouping\nval grouped = numbers.groupBy { it % 2 == 0 }\n// {false=[1, 3, 5], true=[2, 4]}\n\n\n**Sequences for lazy evaluation:**\n\nval result = (1..1000000)\n .asSequence()\n .filter { it % 2 == 0 }\n .map { it * it }\n .take(10)\n .toList()\n\n\n**Array vs List:**\n\nval array = arrayOf(1, 2, 3) // Fixed size, mutable elements\nval list = listOf(1, 2, 3) // Immutable\nval mutableList = mutableListOf(1, 2, 3) // Mutable\n
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback