Kotlin Lambdas and Higher-Order Functions Explained with Examples

When developing modern Android applications using Kotlin and Jetpack Compose, you’ll frequently encounter code that passes functions as arguments.

For example:

Button(
    onClick = {
        println("Button clicked")
    }
) {
    Text("Click Me")
}

Have you ever wondered what the curly braces inside onClick represent?

They contain a lambda expression.

Lambda expressions are among Kotlin’s most important features. They allow us to write functions without giving them names and pass behavior between different parts of an application.

Kotlin also supports higher-order functions, which can receive functions as parameters or return functions as results.

These concepts are widely used in Android development, including:

  • Jetpack Compose button callbacks
  • Collection operations such as filter() and map()
  • Event handling
  • ViewModel interactions
  • Repository callbacks
  • Coroutines
  • Flow transformations
  • Reusable UI components

In this tutorial, we’ll explore Kotlin lambdas and higher-order functions step by step.


What You’ll Learn

By the end of this tutorial, you’ll understand:

  • What lambda expressions are
  • Lambda syntax
  • Lambdas with parameters
  • Lambdas with return values
  • The it keyword
  • Kotlin function types
  • Passing functions as parameters
  • Higher-order functions
  • Functions returning functions
  • Trailing lambda syntax
  • Function references
  • Lambdas with multiple parameters
  • Closures
  • Inline functions
  • Lambdas in Kotlin collections
  • Callbacks in Android development
  • Jetpack Compose button callbacks
  • Building reusable Compose components

Let’s begin!


1. What Is a Lambda Expression in Kotlin?

A lambda expression is an anonymous function that can be stored in a variable, passed as an argument, or executed later.

Unlike a regular function, a lambda does not require a function name.

Regular Kotlin Function

fun greet() {
    println("Hello Kotlin")
}

Call the function:

greet()

Output:

Hello Kotlin

Equivalent Lambda Expression

val greet = {
    println("Hello Kotlin")
}

Execute the lambda:

greet()

Output:

Hello Kotlin

Explanation

The statement:

val greet = { ... }

stores a function in a variable.

We can execute it using:

greet()

This ability to treat functions as values makes Kotlin flexible and expressive.


2. Kotlin Lambda Syntax

The general syntax of a lambda expression is:

val lambdaName = { parameter: Type ->
    // Function body
    result
}

A lambda can contain:

  • Zero or more parameters
  • A function body
  • An optional result expression

Example

val square = { number: Int ->
    number * number
}

Usage

fun main() {

    val square = { number: Int ->
        number * number
    }

    println(square(5))
}

Output:

25

Explanation

The lambda accepts an integer parameter.

The expression:

number * number

produces the result.

The result of the final expression is automatically returned.


3. Kotlin Lambdas with Parameters

Lambda expressions can accept parameters just like regular functions.

Example: Greeting Message

val greetUser = { name: String ->
    println("Welcome, $name")
}

Usage

fun main() {

    val greetUser = { name: String ->
        println("Welcome, $name")
    }

    greetUser("Alex")
    greetUser("Emma")
}

Output:

Welcome, Alex
Welcome, Emma

Example: Addition

val add = { a: Int, b: Int ->
    a + b
}

Usage

println(add(10, 20))

Output:

30

Multiple parameters are separated by commas.


4. Kotlin Lambdas with Return Values

A lambda returns the value of its last expression.

Example

val multiply = { a: Int, b: Int ->
    a * b
}

Usage

fun main() {

    val result = multiply(5, 4)

    println(result)
}

Output:

20

Another Example

val checkEven = { number: Int ->
    number % 2 == 0
}

Usage

println(checkEven(10))
println(checkEven(7))

Output:

true
false

The lambda returns a Boolean value.

Important

A lambda usually returns the result of its final expression. You don’t need to use the return keyword for ordinary lambda results.


5. Kotlin it Keyword in Lambdas

When a lambda has exactly one parameter, Kotlin often allows us to use the implicit parameter name it.

Example Without it

val square = { number: Int ->
    number * number
}

Example Using it

val square: (Int) -> Int = {
    it * it
}

Usage

println(square(6))

Output:

36

Practical Example

val numbers = listOf(1, 2, 3, 4, 5)

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

println(evenNumbers)

Output:

[2, 4]

When Should You Use it?

Use it for short lambdas where the meaning is clear.

For complex lambdas, explicitly naming the parameter can improve readability.


6. What Are Function Types in Kotlin?

Kotlin treats functions as values with specific types.

A function type describes the parameters a function accepts and the value it returns.

Syntax

(ParameterType) -> ReturnType

Examples

Function TypeMeaning
() -> UnitNo parameters, no meaningful result
(Int) -> IntAccepts Int, returns Int
(String) -> BooleanAccepts String, returns Boolean
(Int, Int) -> IntAccepts two Int values, returns Int
(String) -> UnitAccepts String, returns Unit

Example

val calculateSquare: (Int) -> Int = {
    it * it
}

Usage

fun main() {

    println(calculateSquare(7))
}

Output:

49

Explanation

The declaration:

(Int) -> Int

means the function accepts an integer and returns an integer.

Function types are essential for understanding higher-order functions.


7. What Is a Higher-Order Function?

A higher-order function is a function that:

  • Accepts another function as a parameter, or
  • Returns a function as its result.

This allows developers to separate reusable logic from the specific behavior being executed.

Example

fun performAction(action: () -> Unit) {
    action()
}

Usage

fun main() {

    performAction {
        println("Action executed")
    }
}

Output:

Action executed

Explanation

The function:

performAction()

accepts another function through the parameter:

action: () -> Unit

Inside performAction(), the supplied function is executed.

This pattern is commonly used for event handling and callbacks.


8. Passing Lambdas as Function Parameters

Let’s create a calculator using higher-order functions.

Example

fun calculate(
    a: Int,
    b: Int,
    operation: (Int, Int) -> Int
): Int {

    return operation(a, b)
}

Usage

fun main() {

    val sum = calculate(10, 5) { a, b ->
        a + b
    }

    val difference = calculate(10, 5) { a, b ->
        a - b
    }

    val product = calculate(10, 5) { a, b ->
        a * b
    }

    println(sum)
    println(difference)
    println(product)
}

Output:

15
5
50

How It Works

The calculate() function contains reusable logic.

The lambda determines which operation to perform.

This avoids creating separate higher-level functions for every calculation.


9. Kotlin Trailing Lambda Syntax

Kotlin provides a convenient syntax when the final argument of a function is another function.

The lambda can be written outside the parentheses.

Example

fun executeTask(task: () -> Unit) {
    task()
}

Regular Syntax

executeTask({
    println("Task completed")
})

Trailing Lambda Syntax

executeTask {
    println("Task completed")
}

Both versions perform the same operation.

Why Is This Important?

Trailing lambdas are widely used in Jetpack Compose.

For example:

Button(
    onClick = {
        println("Clicked")
    }
) {
    Text("Submit")
}

The trailing lambda defines the button’s content.

This syntax makes declarative UI code easier to read.


10. Higher-Order Functions Returning Functions

Higher-order functions can also return other functions.

Example

fun createMultiplier(
    multiplier: Int
): (Int) -> Int {

    return { number ->
        number * multiplier
    }
}

Usage

fun main() {

    val double = createMultiplier(2)

    val triple = createMultiplier(3)

    println(double(10))
    println(triple(10))
}

Output:

20
30

Explanation

The function:

createMultiplier(2)

returns a new function that multiplies its input by two.

The returned function remembers the multiplier value.

This is an example of a closure.


11. What Are Closures in Kotlin?

A closure is a function that captures variables from its surrounding scope.

Example

fun main() {

    var counter = 0

    val increment = {
        counter++
        println(counter)
    }

    increment()
    increment()
    increment()
}

Output:

1
2
3

Explanation

The lambda accesses and modifies the counter variable declared outside it.

This captured variable remains accessible to the lambda.

Practical Use Cases

Closures are useful for:

  • Event handlers
  • State updates
  • Configurable operations
  • Callback functions
  • Creating specialized functions

Important

When closures capture mutable state, be careful about concurrent access and lifecycle-related memory retention.

In Android development, avoid unnecessarily capturing long-lived references to Activities, Views, or Context objects.


12. Kotlin Function References

Kotlin allows us to refer to existing functions using the :: operator.

Example

fun greet(name: String) {
    println("Hello, $name")
}

Function Reference

val greetingFunction: (String) -> Unit = ::greet

Usage

fun main() {

    greetingFunction("Alex")
}

Output:

Hello, Alex

Practical Example

fun square(number: Int): Int {
    return number * number
}

fun main() {

    val numbers = listOf(1, 2, 3, 4)

    val squares = numbers.map(::square)

    println(squares)
}

Output:

[1, 4, 9, 16]

Why Use Function References?

Function references can make code more readable when an existing function already performs the required operation.


13. Lambdas with Multiple Parameters

A lambda can accept multiple parameters.

Example

val calculateTotal = {
    price: Int,
    quantity: Int ->
    price * quantity
}

Usage

fun main() {

    val total = calculateTotal(500, 3)

    println(total)
}

Output:

1500

Higher-Order Function Example

fun processNumbers(
    first: Int,
    second: Int,
    operation: (Int, Int) -> Int
): Int {

    return operation(first, second)
}

Usage

val result = processNumbers(20, 10) { a, b ->
    a + b
}

println(result)

Output:

30

14. Kotlin Lambdas with Collections

Kotlin collections make extensive use of lambda expressions.

Let’s explore some common operations.

filter()

val numbers = listOf(5, 10, 15, 20)

val filtered = numbers.filter {
    it > 10
}

println(filtered)

Output:

[15, 20]

map()

val numbers = listOf(1, 2, 3)

val doubled = numbers.map {
    it * 2
}

println(doubled)

Output:

[2, 4, 6]

forEach()

val names = listOf("Alex", "Emma", "John")

names.forEach {
    println(it)
}

sortedBy()

data class Product(
    val name: String,
    val price: Int
)

val products = listOf(
    Product("Phone", 15000),
    Product("Mouse", 800),
    Product("Keyboard", 2500)
)

val sortedProducts = products.sortedBy {
    it.price
}

Explanation

In all these examples, lambdas define the behavior performed by the collection function.

This makes Kotlin collection operations concise and expressive.


15. What Are Inline Functions in Kotlin?

Higher-order functions may introduce function objects or indirect function calls.

Kotlin provides the inline keyword, which allows the compiler to substitute a function’s body and eligible lambda bodies at call sites.

Example

inline fun performOperation(
    operation: () -> Unit
) {
    operation()
}

Usage

fun main() {

    performOperation {
        println("Operation completed")
    }
}

Output:

Operation completed

Why Use inline?

Inlining can reduce some overhead associated with higher-order functions.

It can be useful for small functions that accept lambdas.

Important

Do not mark every higher-order function as inline.

Inlining can increase generated code size and may not improve performance in every situation.

Use it when the behavior and performance characteristics justify it.


16. Kotlin noinline and crossinline

Kotlin provides two additional modifiers for lambda parameters in inline functions.

noinline

The noinline modifier prevents a particular lambda parameter from being inlined.

Example:

inline fun executeActions(
    first: () -> Unit,
    noinline second: () -> Unit
) {
    first()
    second()
}

This can be useful when a lambda needs to be stored or passed as a function value.

crossinline

The crossinline modifier prevents non-local returns from the lambda.

Example:

inline fun executeLater(
    crossinline action: () -> Unit
): Runnable {

    return Runnable {
        action()
    }
}

Explanation

The crossinline modifier is useful when an inline lambda is invoked from another execution context, such as a nested object or callback.

These are intermediate Kotlin concepts.

Beginners should first become comfortable with regular lambdas and higher-order functions.


17. Kotlin Lambda vs Anonymous Function

Kotlin supports both lambda expressions and anonymous functions.

Lambda Expression

val square = { number: Int ->
    number * number
}

Anonymous Function

val square = fun(number: Int): Int {
    return number * number
}

Both can represent function values.

Key Difference

Anonymous functions use the fun keyword and support explicit return types.

They also differ from lambdas in how return behaves.

For most simple callbacks and collection transformations, lambda expressions are preferred because they are concise.


18. Practical Android Example: Callback Interface vs Lambda

Before using lambdas, developers often create callback interfaces.

Callback Interface

interface OnTaskCompleteListener {

    fun onComplete(message: String)
}

Function Using the Interface

fun performTask(
    listener: OnTaskCompleteListener
) {

    listener.onComplete("Task completed")
}

This approach is valid, especially when multiple callback methods or a reusable contract are required.

However, for a single callback, a lambda can simplify the implementation.

Lambda-Based Callback

fun performTask(
    onComplete: (String) -> Unit
) {

    onComplete("Task completed")
}

Usage

fun main() {

    performTask { message ->
        println(message)
    }
}

Output:

Task completed

Benefits

  • Less boilerplate code
  • Easy callback implementation
  • Clear function contracts
  • Convenient event handling
  • Useful for reusable UI components

19. Practical Android Example: Reusable Validation Function

Let’s create a reusable validation function using a lambda.

Step 1: Define the Function

fun validateInput(
    input: String,
    validator: (String) -> Boolean
): Boolean {

    return validator(input)
}

Step 2: Validate Username

val isValidUsername = validateInput("Alex123") {
    it.length >= 5
}

Step 3: Validate Password Length

val isValidPassword = validateInput("Password123") {
    it.length >= 8
}

Step 4: Display Results

fun main() {

    println(isValidUsername)

    println(isValidPassword)
}

Output:

true
true

Explanation

The validation function does not need to know which validation rule is being applied.

The caller provides the required behavior.

This is a simple example of using higher-order functions to create reusable logic.

Note: Password length checks alone are not sufficient for production authentication security. Real applications should follow current authentication and password-handling best practices.


20. Jetpack Compose Mini-Project: Reusable Counter Component

Let’s build a simple Jetpack Compose application demonstrating lambda callbacks and higher-order functions.

Our screen will contain:

  • A counter value
  • An Increment button
  • A Decrement button
  • A Reset button
  • A reusable CounterButton component

The reusable component will receive a lambda callback.

Step 1: Create the Reusable Button

@Composable
fun CounterButton(
    title: String,
    onClick: () -> Unit
) {

    Button(
        onClick = onClick
    ) {
        Text(title)
    }
}

Explanation

The parameter:

onClick: () -> Unit

represents a function that accepts no parameters and returns Unit.

The caller decides what happens when the button is clicked.

Step 2: Create the Counter Screen

@Composable
fun CounterDemoScreen() {

    var counter by rememberSaveable {
        mutableIntStateOf(0)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(
            text = "Kotlin Lambda Demo",
            style = MaterialTheme.typography.headlineMedium
        )

        Spacer(
            modifier = Modifier.height(24.dp)
        )

        Text(
            text = "$counter",
            style = MaterialTheme.typography.displayLarge,
            color = MaterialTheme.colorScheme.primary
        )

        Spacer(
            modifier = Modifier.height(24.dp)
        )

        Row(
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {

            CounterButton(
                title = "−",
                onClick = {
                    counter--
                }
            )

            CounterButton(
                title = "+",
                onClick = {
                    counter++
                }
            )
        }

        Spacer(
            modifier = Modifier.height(16.dp)
        )

        CounterButton(
            title = "Reset",
            onClick = {
                counter = 0
            }
        )
    }
}

Step 3: Required Imports

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

Expected UI

+--------------------------------+
|                                |
|                                |
|       Kotlin Lambda Demo       |
|                                |
|               0                |
|                                |
|          [ − ]  [ + ]          |
|                                |
|             [Reset]            |
|                                |
|                                |
+--------------------------------+

How It Works

The screen maintains the counter value using:

var counter by rememberSaveable {
    mutableIntStateOf(0)
}

The reusable CounterButton receives an onClick lambda.

For example:

CounterButton(
    title = "+",
    onClick = {
        counter++
    }
)

When the user taps the button, the lambda executes and updates the counter.

Jetpack Compose observes the state change and updates the displayed value.

Why Is This Important?

This pattern is fundamental to Jetpack Compose development.

Reusable composables should receive callbacks instead of directly controlling unrelated screen logic.

This improves:

  • Reusability
  • Testability
  • Separation of concerns
  • State management
  • UI component design

21. Jetpack Compose State Hoisting with Lambdas

A common Compose design pattern is state hoisting.

Instead of allowing every UI component to manage its own state, we can pass the state and event callbacks from a parent component.

Example

@Composable
fun CounterContent(
    count: Int,
    onIncrement: () -> Unit,
    onDecrement: () -> Unit
) {

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(
            text = "$count",
            style = MaterialTheme.typography.headlineLarge
        )

        Row {

            Button(
                onClick = onDecrement
            ) {
                Text("−")
            }

            Button(
                onClick = onIncrement
            ) {
                Text("+")
            }
        }
    }
}

Parent Composable

@Composable
fun CounterScreen() {

    var count by rememberSaveable {
        mutableIntStateOf(0)
    }

    CounterContent(
        count = count,
        onIncrement = {
            count++
        },
        onDecrement = {
            count--
        }
    )
}

Explanation

The parent owns the state.

The child receives:

count: Int

and callbacks:

onIncrement: () -> Unit
onDecrement: () -> Unit

This separates UI presentation from state ownership.

State hoisting is an important concept in modern Android architecture.


22. Common Kotlin Lambda Mistakes

Mistake 1: Confusing Function Execution with Function References

Consider:

fun greet() {
    println("Hello")
}

If a function parameter expects a callback, use a function reference when appropriate:

val action: () -> Unit = ::greet

Calling:

greet()

executes the function immediately.

Mistake 2: Forgetting Lambda Parameter Types

If Kotlin cannot infer a lambda parameter type, specify the function type or parameter type.

Example:

val square: (Int) -> Int = {
    it * it
}

Mistake 3: Overusing it

For complex lambdas, explicit parameter names improve readability.

Instead of:

products.filter {
    it.price > 1000 && it.category == "Electronics"
}

You can write:

products.filter { product ->
    product.price > 1000 &&
        product.category == "Electronics"
}

Mistake 4: Creating Unnecessary Nested Lambdas

Deeply nested lambdas can become difficult to understand.

Consider extracting complex logic into named functions.

Mistake 5: Capturing Long-Lived Android References

Be careful when lambdas are stored by long-lived objects.

Capturing an Activity or View unnecessarily can contribute to memory leaks.

Mistake 6: Executing Expensive Work Directly in UI Callbacks

Avoid performing heavy database, network, or CPU-intensive operations directly on the Android main thread.

Use appropriate asynchronous APIs, ViewModel, and coroutines for long-running work.


23. Kotlin Lambdas Best Practices

Follow these recommendations:

  • Use lambdas for concise callbacks and transformations.
  • Prefer descriptive parameter names in complex expressions.
  • Use function references when they improve readability.
  • Avoid unnecessary nested higher-order functions.
  • Keep reusable functions focused on one responsibility.
  • Use immutable values when practical.
  • Avoid capturing unnecessary lifecycle-sensitive references.
  • Use state hoisting for reusable Compose components.
  • Keep expensive work away from the main thread.
  • Use inline only when appropriate.
  • Write unit tests for reusable higher-order functions.
  • Prefer clear code over overly clever functional expressions.

These practices help create maintainable Kotlin and Android applications.


24. Kotlin Lambdas Quick Reference

ConceptExample
Simple lambdaval action = { println("Hi") }
Lambda with parameter{ x: Int -> x * 2 }
Lambda with two parameters{ a: Int, b: Int -> a + b }
Function type(Int) -> Int
Callback type() -> Unit
Higher-order functionfun run(action: () -> Unit)
Trailing lambdarun { println("Done") }
Function reference::greet
Implicit parameterit
Filter lambdafilter { it > 10 }
Map lambdamap { it * 2 }
Inline functioninline fun execute(...)
Compose callbackonClick = { ... }

25. Practical Exercises

Try these exercises to improve your Kotlin skills.

Exercise 1: Simple Lambda

Create a lambda that accepts an integer and returns its cube.

Exercise 2: Calculator

Create a higher-order function that accepts two numbers and an operation lambda.

Support:

  • Addition
  • Subtraction
  • Multiplication
  • Division

Exercise 3: String Validation

Create a reusable validation function that accepts a String and a lambda.

Use it to validate usernames and email input.

Exercise 4: Collection Filtering

Create a list of numbers.

Use filter() to select numbers greater than 50.

Exercise 5: Function Reference

Create a function that converts a String to uppercase.

Pass the function reference to map().

Exercise 6: Callback Function

Create a function that accepts an onSuccess callback.

Execute the callback after completing a simulated task.

Exercise 7: Jetpack Compose Counter

Create a counter screen using:

  • rememberSaveable
  • mutableIntStateOf
  • Reusable Button composable
  • Lambda callbacks
  • State hoisting

What We’ve Learned

In this tutorial, we learned:

  • Kotlin lambda expressions
  • Lambda syntax
  • Lambdas with parameters
  • Lambda return values
  • The it keyword
  • Function types
  • Higher-order functions
  • Passing functions as parameters
  • Returning functions
  • Trailing lambda syntax
  • Closures
  • Function references
  • Inline functions
  • noinline and crossinline
  • Anonymous functions
  • Lambdas with collections
  • Android callbacks
  • Jetpack Compose event handling
  • Reusable composables
  • State hoisting
  • Common mistakes and best practices

Lambda expressions and higher-order functions are essential features of Kotlin.

They are especially important when building modern Android applications using Jetpack Compose, Coroutines, Flow, and Clean Architecture.

Understanding these concepts will make it easier to write reusable UI components, process collections, handle events, and design maintainable application logic.


What’s Next?

In our next tutorial, we’ll explore:

Kotlin Extension Functions and Properties Explained with Examples

You’ll learn:

  • What extension functions are
  • Creating extension functions
  • Extension properties
  • Nullable receiver extensions
  • Generic extension functions
  • Extension functions vs member functions
  • Scope and resolution rules
  • Practical Android utility extensions
  • Jetpack Compose extension patterns
  • Best practices and common mistakes

Happy Coding!

Continue learning modern Android development with Moiks Developer Blog.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment