Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 134 ยท Functions

Local and Nested Functions

Learn Kotlin local functions - declaring functions inside functions, capturing variables as closures, declaration order, recursion, and when a local function beats a private helper.

Sometimes a helper is only useful inside one other function. Maybe it removes a repeated bit of code, or it names a step that makes the main logic easier to read. Putting such a helper at the top level of the file pollutes the namespace with something no one else should call. Kotlin lets you do the sensible thing instead: declare the function inside the function that needs it. This is a local function.

Local functions have one more power that top-level functions lack: they can read, and even change, the variables of the function around them. That is called capturing, and it is the same mechanism that makes lambdas so convenient. This lesson explains how local functions work, what they can see, the rules about order and recursion, and how to decide between a local function, a private function and a lambda.

A function inside a function

Declare the local function with fun like any other, but place it in the body of another function. Only the code after the declaration, in that same block, can call it.

Kotlin A local helper that removes repetition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output has four aligned lines: Student Ada, Count 3, Best 100 and Average 85.0. The format string %-10s pads the label to ten characters. The function line exists only inside printReport; if you try to call it from main, the compiler reports an unresolved reference. The helper is hidden from the rest of the program, so it can never be misused from elsewhere.

Closures: capturing the outer scope

A local function can use anything that is visible where it is declared: the outer function's parameters and its local variables. This is called a closure, because the function "closes over" the variables around it. You don't pass those values in as arguments; they are simply there.

Kotlin A local function reads outer variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here clean does not use suffix, but the return line does, and nothing prevented clean from reading it. The two calls print Paris, France and Tokyo, Japan (express).

More interesting is that a local function can modify a captured var. Kotlin lets it, because the captured variable is really shared, not copied:

Kotlin A local function changes an outer var

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

addWordsOf updates total directly, and the surrounding function sees the final count: 9. The four sentences have four, two, zero and three words. This is very convenient, but mutating outer state from inside a helper can make code harder to follow. When you can, prefer a local function that returns a value, like fun wordsIn(text: String): Int, and add the results in the caller.

How it works under the hood

On the JVM, a local function that captures a var forces the compiler to store that variable in a small box object (a Ref) that both functions share. A local function that captures nothing, or only vals, avoids the box. So capturing mutable variables costs an allocation per call of the outer function. It's small, but it is the reason hot loops should not create closures that capture a var on every iteration.

Order matters: declare before you use

Unlike top-level and member functions, which you can call before their declaration, a local function must be declared above the code that uses it. A local function behaves like a local variable here.

Kotlin Calling a local function too early (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers main.kt:2:13: error: unresolved reference 'double'. The name does not exist yet at that line. Moving the declaration up fixes it:

Kotlin
fun main() {
    fun double(x: Int) = x * 2
    println(double(4))
}

Recursion in a local function

A local function may call itself, which is useful when a helper needs extra bookkeeping state that the public function should not expose. Because a recursive function cannot infer its own return type, you must write it.

Kotlin A recursive local function with a hidden accumulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are 120, 3628800 and 2432902008176640000. Callers see the simple signature factorial(n), while go carries the accumulator acc that makes the recursion work. This pattern pairs well with tailrec, which the recursion lesson covers: mark go as tailrec and the compiler turns it into a loop.

Nested functions in classes and objects

Two other things are sometimes called nested. A member function is declared in a class body and is not local, because it exists as long as the class does. A local function in the strict sense lives in a function body. You can also place local functions inside lambdas, init blocks and property accessors, anywhere a block of statements is allowed.

Local functions can be generic and can have default arguments, just like other functions:

Kotlin Local functions are full functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [1.0] <9.25> [3 items]. The local bracket is generic in T, takes two defaults, and the third call uses a named argument to replace only the closing text, so it prints [3 items].

Local function, lambda or private function?

Kotlin gives you several ways to write "a bit of reusable code in one place". Here is a quick guide.

Tool Use it when
Local function The helper has a clear name, is used in more than one place inside one function, and needs the outer variables
Lambda The code is passed to something else (map, forEach, a callback) or is a one-liner
private top-level or member function The helper is long, is useful to several functions, or needs its own unit test

A named local function usually reads better than a lambda stored in a val, because the name appears in stack traces and you can use recursion and default arguments. Compare:

Kotlin Local function versus a lambda in a val

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first part prints parsed: [12, 7, 40] and rejected: 2. A local function can be passed around with a callable reference (::parseOrNull), which gives you the best of both: a name and a function value. The lambda version prints the same list, [12, 7, 40], but cannot count its rejects without extra code. (Callable references are covered in Higher-Order Functions.)

Pitfalls and good habits

  • Do not nest deeply. A local function inside a local function inside a function is a sign that the outer function is doing too much. Extract a private function instead.
  • Beware of long local functions. They inflate the enclosing function and make it hard to test. Two or three lines is a good size.
  • Mind the lifetime of captured variables. If a closure escapes (you return it, or store it in a field), the captured variables stay alive as long as the closure does. A closure capturing a large list can keep it in memory.
  • Shadowing is allowed but confusing. A parameter of a local function may have the same name as an outer variable; the compiler warns about it. Use a different name.

A local function that doesn't use any outer variable is just a private function in disguise. If you find yourself wanting to unit test it, or call it from a second function, move it out. A local function earns its place by capturing the surroundings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where can a local function be called?

    A local function is visible only inside the block where it is declared, and only below its declaration, like a local variable.
  2. 2. What is a closure?

    A closure captures variables of the surrounding scope. Local functions and lambdas are closures.
  3. 3. What does the compiler report for calling a local function before it is declared?

    The name does not exist yet at that point of the function body, so it is an unresolved reference.
  4. 4. Why must a recursive local function declare its return type?

    With an expression body, the return type would depend on the recursive call itself. You break the cycle by writing the type.
  5. 5. A local function increments a captured var total. What does the outer function see afterwards?

    Captured variables are shared, not copied. Kotlin boxes a captured var so both functions work on the same storage.

Summary

  • A local function is declared inside another function and is visible only there, after its declaration.
  • It can read and modify the outer function's parameters and variables (a closure); a captured var is boxed on the JVM.
  • Local functions can be recursive (with an explicit return type), generic, and can use defaults and named arguments.
  • Use one when a helper is tiny, needs the outer variables or would only clutter the file; use a private function when it grows or needs its own tests.
  • Prefer helpers that return values over helpers that mutate captured variables.

Next: Lambdas