Thuta Learning
AdvancedProgrammingbeginner

Higher-Order Functions

Relax. We'll talk through this in plain words — no textbook voice.

A higher-order function is one that can take a function as a parameter, or return a function. It's essential when writing Kotlin in a functional programming style. You'll see it constantly in things like collection filtering, transformation, and event handling.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)

    val evenNumbers = numbers.filter { it % 2 == 0 }
    val squaredNumbers = numbers.map { it * it }

    println("Even numbers: $evenNumbers")
    println("Squared numbers: $squaredNumbers")
}
You should see
Even numbers: [2, 4] Squared numbers: [1, 4, 9, 16, 25]

Summary

Once you can use higher-order functions, you can process data lists in a style that's both concise and powerful.

Easy traps

  • It's easy to mix up filter and map. Just remember: filter = pick out, map = transform.

Practical example — active users

Practical example — active users

kotlin
data class User(val name: String, val active: Boolean)

fun main() {
    val users = listOf(
        User("Aung", true),
        User("Hla", false),
        User("Su", true)
    )

    val activeNames = users
        .filter { it.active }
        .map { it.name }

    println(activeNames)
}

You'll know it worked when: [Aung, Su]

Higher-Order Functions | Thuta Learning