0
0
Kotlinprogramming~5 mins

Returning functions from functions in Kotlin

Choose your learning style9 modes available
Introduction

Sometimes you want a function to create and give you another function to use later. This helps keep your code neat and flexible.

When you want to create a custom calculator that changes behavior based on input.
When you need to delay some work until later but decide what work to do now.
When you want to build small reusable pieces that can be combined in different ways.
When you want to create a function that remembers some information and uses it later.
Syntax
Kotlin
fun outerFunction(): (Int) -> Int {
    return fun(innerValue: Int): Int {
        return innerValue * 2
    }
}

The outer function returns another function as its result.

The returned function can take parameters and return a value.

Examples
This function returns another function that multiplies its input by a given factor.
Kotlin
fun makeMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}
This function returns a function that greets the given name when called.
Kotlin
fun greeter(name: String): () -> String {
    return { "Hello, $name!" }
}
Sample Program

This program creates a function that adds 5 to any number. Then it uses that function to add 5 to 10 and 3.

Kotlin
fun makeAdder(x: Int): (Int) -> Int {
    return { y -> x + y }
}

fun main() {
    val addFive = makeAdder(5)
    println(addFive(10))
    println(addFive(3))
}
OutputSuccess
Important Notes

You can use lambda expressions to return functions easily.

Returned functions can capture variables from the outer function (called closures).

Summary

Functions can return other functions to create flexible and reusable code.

Returned functions can take parameters and use values from the outer function.