Lists, Sets, and Maps
Kotlin's three core collection types, and the mutable/read-only distinction that runs through all of them.
読了時間 2 分
Kotlin's standard library builds on three familiar collection shapes — List, Set, and Map — but adds one idea that runs through every one of them: a clear split between read-only and mutable versions.
Lists
A List is an ordered collection that can contain duplicates:
val languages = listOf("Kotlin", "Swift", "Rust", "Kotlin")
println(languages[0]) // Kotlin
println(languages.size) // 4
println("Rust" in languages) // truelistOf(...) creates a read-only list — there's no .add() or .remove() available on it at all. For a list you intend to modify, use mutableListOf(...):
val scores = mutableListOf(10, 20, 30)
scores.add(40)
scores.removeAt(0)
println(scores) // [20, 30, 40]Sets
A Set stores unique values with no guaranteed order — adding a duplicate has no effect:
val uniqueTags = setOf("android", "kotlin", "android")
println(uniqueTags) // [android, kotlin]
println(uniqueTags.size) // 2
val mutableTags = mutableSetOf("android")
mutableTags.add("kotlin")
mutableTags.add("android") // no-op — already presentReach for a Set whenever "does this collection already contain X?" matters more than order — membership checks on a Set are typically far faster than scanning a List.
Maps
A Map associates keys with values, similar to a dictionary or hash map in other languages:
val userAges = mapOf("Alice" to 30, "Bob" to 25)
println(userAges["Alice"]) // 30
println(userAges["Charlie"]) // null — key doesn't exist
println(userAges.containsKey("Bob")) // trueto here is an infix function that builds a Pair — "Alice" to 30 is just a readable way of writing Pair("Alice", 30). As with the other collection types, mutableMapOf gives you a version you can update:
val inventory = mutableMapOf("apples" to 10, "bananas" to 5)
inventory["apples"] = 15 // update
inventory["cherries"] = 20 // insert
inventory.remove("bananas")
println(inventory) // {apples=15, cherries=20}Iterating
All three types work with for, and Map gives you the key and value together:
for (language in languages) {
println(language)
}
for ((name, age) in userAges) {
println("$name is $age years old")
}Why the read-only/mutable split matters
listOf, setOf, and mapOf don't promise the underlying data can never change (another part of the code holding a MutableList reference to the same object still could) — but they promise that the code holding the read-only reference can't accidentally mutate it. Passing a plain List into a function, rather than a MutableList, is a way of documenting — and having the compiler enforce — "this function only reads this data, it doesn't change it."
Creating and updating collections is only half the story. The next lesson covers map, filter, reduce, and the other functional operations that let you transform a collection's contents in a single readable line.