Collections & Lambdas
Lists, sets, and maps are read-only by default, and functional operations like map/filter/forEach take lambdas — with it standing in for an unnamed single parameter.
List, Set, and Map
Kotlin's standard collections are read-only by default — listOf(), setOf(), and mapOf() create immutable collections, with mutableListOf() and friends for when you need to change them:
fun main() {
val fruits = listOf("apple", "banana", "cherry")
val prices = mapOf("apple" to 1.5, "banana" to 0.5)
println(fruits[1])
println(prices["apple"])
}
banana 1.5
to is how Kotlin builds a key-value pair inline for mapOf() — it's a real function under the hood, not special syntax.
Lambdas with map, filter, and forEach
Kotlin's collections come with functional-style operations that take a lambda — code in curly braces you pass around like a value:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val doubled = numbers.map { it * 2 }
val evens = numbers.filter { it % 2 == 0 }
println(doubled)
println(evens)
numbers.forEach { n -> print("$n ") }
println()
}
[2, 4, 6, 8, 10, 12] [2, 4, 6] 1 2 3 4 5 6
it is an automatic name Kotlin gives a lambda's single parameter when you don't name one yourself — { it * 2 } and { n -> n * 2 } mean exactly the same thing. map transforms every element, filter keeps only the ones matching a condition, and none of them modify the original list — each returns a new one.