0
0
Kotlinprogramming~3 mins

Why Passing lambdas to functions in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could teach your functions new tricks without rewriting them every time?

The Scenario

Imagine you want to perform different actions on a list of numbers, like doubling them or checking if they are even. Without lambdas, you'd have to write separate functions for each action and call them manually every time.

The Problem

This manual way is slow and repetitive. You end up writing lots of similar code, which is easy to mess up and hard to change later. It feels like doing the same chore over and over without any shortcuts.

The Solution

Passing lambdas to functions lets you send little pieces of code as arguments. This means you can write one flexible function and tell it exactly what to do each time, without rewriting the whole thing.

Before vs After
Before
fun double(numbers: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (n in numbers) {
        result.add(n * 2)
    }
    return result
}

fun even(numbers: List<Int>): List<Int> {
    val result = mutableListOf<Int>()
    for (n in numbers) {
        if (n % 2 == 0) result.add(n)
    }
    return result
}
After
fun process(numbers: List<Int>, action: (Int) -> Unit) {
    for (n in numbers) {
        action(n)
    }
}

process(listOf(1,2,3)) { println(it * 2) }
process(listOf(1,2,3)) { if (it % 2 == 0) println(it) }
What It Enables

You can write one powerful function that adapts to many tasks by simply passing different lambdas, making your code cleaner and easier to maintain.

Real Life Example

Think about a music app that plays songs differently based on user mood. Instead of writing separate play functions, it can accept a lambda to customize how each song plays, like adding effects or skipping tracks.

Key Takeaways

Manual repetition is slow and error-prone.

Lambdas let you pass custom actions into functions.

This makes code flexible, reusable, and easier to change.