BeginnerLesson 6 of 16
Lists, Sets & Maps – Kotlin
The basic Kotlin collection types – read-only or mutable.
Kotlin separates read-only and mutable collections: listOf creates a read-only list (no add), mutableListOf a mutable one. You access elements with [].
val zahlen = listOf(3, 1, 2) // read-only
val mutabel = mutableListOf(3, 1, 2)
mutabel.add(5)
mutabel.sort()
println("$mutabel ${mutabel[0]} ${mutabel.last()} ${mutabel.size}") // [1, 2, 3, 5] 1 5 4
println(zahlen.sorted()) // [1, 2, 3]
println(zahlen + 4) // [3, 1, 2, 4] (new list)
println(2 in zahlen) // trueYou create maps with mapOf or mutableMapOf and pairs (key to value). Sets store each value only once.
val alter = mutableMapOf("Ada" to 36, "Bob" to 25)
alter["Cy"] = 41
alter["Bob"] = alter.getValue("Bob") + 1
println(alter) // {Ada=36, Bob=26, Cy=41}
println(alter["Dora"]) // null
println(alter["Dora"] ?: -1) // -1
for ((name, a) in alter) println("$name: $a")
val einzigartig = setOf(3, 1, 2, 2, 3)
println(einzigartig) // [3, 1, 2]
val feld = arrayOf("a", "b") // fixed-size arrayWarning
listOf returns only a read-only view: if you pass a MutableList on as a List, it can still be modified. And map[key] returns null if the key is missing – so the type is nullable.Tip
+ and - on lists create new lists. With += on a var list you assign the new list, whereas on a val MutableList the element is added directly.