Lists and maps in Kotlin
Read-only by default, mutable by request.
fun main() {
// listOf is read-only; mutableListOf accepts changes.
val stops = listOf("Aspen Gate", "Windy Col", "The Cirque")
println(stops[1])
val pack = mutableListOf("map", "stove")
pack.add("headlamp")
println("${pack.size} items packed")
// mapOf pairs keys with to; indexing a missing key gives null.
val beds = mapOf("Larkspur Hut" to 18, "Stone Shelter" to 6)
println(beds["Stone Shelter"])
println(beds["Bivy Ledge"])
}
How it works
listOfbuilds a fixed list; indexing uses square brackets.mutableListOfacceptsadd, andsizetracks it.mapOf("a" to 1)pairs keys withto; a missing key indexes to null.
Keywords and builtins used here
funmainval
The run, in numbers
- Lines
- 13
- Characters to type
- 431
- Tokens
- 100
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 86 seconds.
Step 1 of 3 in Collections, step 10 of 27 in Language basics.