Collections and Lambdas

Harry · 14 Sep 2026 · 2 views
Advertisement
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
  • filter keeps elements matching a condition.
  • map transforms each element.
  • reduce/fold/sum combine elements into one result.
  • groupBy, sortedBy, find, any, count cover 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/mapOf are read-only; the mutable* variants can change.
  • Lambdas are functions in braces; it is the single argument.
  • Chain filter, map and reduce to process data declaratively.
  • Higher-order functions replace most explicit loops.
Share this post:

Comments (0)

Please login or register to comment.