0
0
Kotlinprogramming~5 mins

Higher-order function declaration in Kotlin

Choose your learning style9 modes available
Introduction

A higher-order function is a function that can take other functions as input or return a function. It helps us write flexible and reusable code.

When you want to run different actions on the same data without repeating code.
When you want to customize behavior by passing small pieces of code as arguments.
When you want to create functions that build or return other functions.
When you want to handle events or callbacks in a clean way.
When you want to simplify complex logic by breaking it into smaller functions.
Syntax
Kotlin
fun functionName(parameter: (Type) -> ReturnType): ReturnType {
    // function body
}

// or a function returning another function
fun functionName(): (Type) -> ReturnType {
    return { parameter -> 
        // function body
    }
}

The parameter with type like (Type) -> ReturnType means it expects a function.

You can pass lambda expressions or named functions as arguments.

Examples
This function takes a number and another function that changes the number, then returns the result.
Kotlin
fun operateOnNumber(x: Int, operation: (Int) -> Int): Int {
    return operation(x)
}
Here, we define a function double and pass it to operateOnNumber.
Kotlin
val double: (Int) -> Int = { it * 2 }

val result = operateOnNumber(5, double)
This function returns another function that multiplies by a given factor.
Kotlin
fun makeMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}
Sample Program

This program shows a higher-order function operateOnNumber that takes a number and a function to apply to it. We pass two different functions to see different results.

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

fun main() {
    val double: (Int) -> Int = { it * 2 }
    val square: (Int) -> Int = { it * it }

    println(operateOnNumber(4, double))  // prints 8
    println(operateOnNumber(4, square))  // prints 16
}
OutputSuccess
Important Notes

Higher-order functions make your code more flexible and easier to change.

Use lambda expressions to quickly create small functions to pass around.

Remember to keep your function types clear to avoid confusion.

Summary

Higher-order functions can take functions as parameters or return them.

They help reuse code by allowing different behaviors to be passed in.

Kotlin uses function types like (Type) -> ReturnType to declare these.