0
0
Kotlinprogramming~5 mins

Passing lambdas to functions in Kotlin

Choose your learning style9 modes available
Introduction

Lambdas let you send small pieces of code to functions. This makes your code flexible and easy to change.

When you want to run different actions inside the same function.
When you want to handle events like button clicks in Android apps.
When you want to filter or transform lists quickly.
When you want to write cleaner and shorter code without making many functions.
Syntax
Kotlin
fun functionName(action: (Type) -> ReturnType) {
    // use action inside
    val value: Type = TODO()
    val result = action(value)
    // do something with result
}

The lambda is passed as a parameter inside parentheses.

The lambda type shows input and output types: (Type) -> ReturnType.

Examples
This function takes a lambda that gets a String and returns nothing (Unit). It prints "Hello".
Kotlin
fun greet(action: (String) -> Unit) {
    action("Hello")
}

greet { message ->
    println(message)
}
This function takes a number and a lambda that doubles it. It prints 10.
Kotlin
fun calculate(x: Int, operation: (Int) -> Int): Int {
    return operation(x)
}

val result = calculate(5) { it * 2 }
println(result)
Sample Program

This program shows how to pass lambdas to add and multiply two numbers. It prints the results.

Kotlin
fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

fun main() {
    val sum = applyOperation(4, 5) { a, b -> a + b }
    val product = applyOperation(4, 5) { a, b -> a * b }
    println("Sum: $sum")
    println("Product: $product")
}
OutputSuccess
Important Notes

You can use the 'it' keyword if the lambda has only one parameter.

Lambdas make your functions more reusable and clear.

Summary

Lambdas are small blocks of code you can pass to functions.

They help make your code flexible and shorter.

Use lambdas to customize what a function does without changing the function itself.