Collections and Lambdas
Harry
· 14 Sep 2026
· 2 views
Advertisement
Creating collections
Kotlin separates read-only from mutable collections at the type level:
val nums = listOf(1, 2, 3, 4) // read-only List
val set = setOf("a", "b") // read-only Set
val map = mapOf("x" to 1, "y" to 2) // read-only Map
val bag = mutableListOf(1, 2) // can add/remove
bag.add(3)
Lambdas
A lambda is a function you can pass around, written in braces. Inside a single-parameter lambda, it refers to the argument:
val square = { n: Int -> n * n }
println(square(5)) // 25
nums.forEach { println(it) } // 'it' is each element
Transforming data
The functional operators replace verbose loops. They read like a description of what you want:
val result = nums
.filter { it % 2 == 0 } // keep evens -> [2, 4]
.map { it * 10 } // transform -> [20, 40]
.sum() // reduce -> 60
filterkeeps elements matching a condition.maptransforms each element.reduce/fold/sumcombine elements into one result.groupBy,sortedBy,find,any,countcover most other needs.
A worked example
data class Emp(val name: String, val dept: String, val salary: Int)
val byDept = staff
.filter { it.salary > 50000 }
.groupBy { it.dept }
.mapValues { (_, list) -> list.map { it.name } }
Key points
listOf/setOf/mapOfare read-only; themutable*variants can change.- Lambdas are functions in braces;
itis the single argument. - Chain
filter,mapandreduceto process data declaratively. - Higher-order functions replace most explicit loops.