0
0
Kotlinprogramming~5 mins

Local functions (nested functions) in Kotlin

Choose your learning style9 modes available
Introduction

Local functions help organize code by putting small helper functions inside bigger ones. This keeps related code together and easier to read.

When you want to break a big function into smaller steps without making those steps visible outside.
When a helper function is only useful inside one main function.
When you want to avoid cluttering the outer scope with functions used only once.
When you want to improve code readability by grouping related logic.
When you want to use variables from the outer function directly inside the helper function.
Syntax
Kotlin
fun outerFunction() {
    fun localFunction() {
        // code here
    }
    localFunction()
}

Local functions are defined inside another function.

They can access variables from the outer function.

Examples
A simple local function that prints a greeting.
Kotlin
fun greet() {
    fun sayHello() {
        println("Hello!")
    }
    sayHello()
}
Local function uses a variable from the outer function.
Kotlin
fun calculate() {
    val base = 10
    fun addFive(x: Int): Int {
        return x + 5 + base
    }
    println(addFive(3))
}
Shows calling a local function in the middle of outer function code.
Kotlin
fun outer() {
    fun inner() {
        println("Inside inner function")
    }
    println("Before calling inner")
    inner()
    println("After calling inner")
}
Sample Program

This program defines a local function printTwice inside printMessage. It prints the message two times using the local function.

Kotlin
fun printMessage() {
    val message = "Kotlin is fun!"
    fun printTwice() {
        println(message)
        println(message)
    }
    printTwice()
}

fun main() {
    printMessage()
}
OutputSuccess
Important Notes

Local functions cannot be called from outside their outer function.

They help keep code clean and avoid repeating code.

Local functions can access and modify variables from the outer function.

Summary

Local functions are functions inside other functions.

They help organize code and keep helper functions private.

They can use variables from the outer function easily.