Bird
Raised Fist0
Kotlinprogramming~10 mins

Local functions (nested functions) in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Local functions (nested functions)
Start outer function
↓
Define local function
↓
Call local function
↓
Local function executes
↓
Return from outer function
The outer function starts, defines a local function inside it, calls this local function, then finishes.
Execution Sample
Kotlin
fun greet(name: String) {
    fun sayHello() {
        println("Hello, $name!")
    }
    sayHello()
}
Defines a function greet with a nested local function sayHello that prints a greeting using the outer function's parameter.
Execution Table
StepActionEvaluationOutput
1Call greet("Alice")Outer function starts
2Define local function sayHellosayHello is ready to use
3Call sayHello()sayHello executesHello, Alice!
4sayHello returnsControl back to greet
5greet returnsFunction ends
💡 greet function finishes after calling local function sayHello
Variable Tracker
VariableStartAfter greet callAfter sayHello callFinal
nameundefined"Alice""Alice""Alice"
sayHelloundefinedfunction definedfunction executedfunction no longer used
Key Moments - 2 Insights
Why can sayHello access the variable 'name'?
Because sayHello is defined inside greet, it can use greet's parameters like 'name' as shown in execution_table step 3.
Can sayHello be called outside greet?
No, sayHello is local to greet and only exists during greet's execution, as seen in execution_table steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 3?
A"Hello, World!"
B"Hello, Alice!"
CNo output
DError
💡 Hint
Check the Output column at step 3 in the execution_table.
At which step does the local function sayHello get defined?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Action column in execution_table for when sayHello is defined.
If we try to call sayHello outside greet, what happens?
AIt causes an error
BIt works normally
CIt prints "Hello, Alice!" anyway
DIt calls greet automatically
💡 Hint
Refer to key_moments about scope and local function accessibility.
Concept Snapshot
Local functions are functions defined inside another function.
They can access outer function variables.
They only exist during the outer function's execution.
Use them to organize code inside a function.
Syntax: define function inside another with fun keyword.
Call local function like any other function inside outer function.
Full Transcript
This example shows a Kotlin function greet that has a local function sayHello inside it. When greet is called with a name, it defines sayHello, which prints a greeting using the name parameter. Then greet calls sayHello, which prints "Hello, Alice!". After that, sayHello returns control to greet, and greet finishes. The local function can use variables from the outer function because it is nested inside it. However, sayHello cannot be called outside greet because it only exists inside greet's scope. This helps keep code organized and limits function visibility.

Practice

(1/5)
1. What is a local function in Kotlin?
easy
A. A function defined outside any class
B. A function defined inside another function
C. A function that can only return integers
D. A function that must be public

Solution

  1. Step 1: Understand function placement

    Local functions are defined inside other functions, not at the top level or in classes.
  2. Step 2: Identify the correct definition

    A function defined inside another function correctly states that a local function is inside another function, which matches Kotlin's definition.
  3. Final Answer:

    A function defined inside another function -> Option B
  4. Quick Check:

    Local function = function inside function [OK]
Hint: Local functions are nested inside other functions [OK]
Common Mistakes:
  • Thinking local functions are top-level
  • Confusing local functions with anonymous functions
  • Assuming local functions must be public
2. Which of the following is the correct syntax to declare a local function inside a Kotlin function?
easy
A. fun outer() { fun inner() { println("Hi") } }
B. fun outer() { def inner() { println("Hi") } }
C. fun outer() { function inner() { println("Hi") } }
D. fun outer() { inner() fun { println("Hi") } }

Solution

  1. Step 1: Recall Kotlin function syntax

    Kotlin uses the keyword 'fun' to declare functions, including local ones.
  2. Step 2: Check each option

    fun outer() { fun inner() { println("Hi") } } uses 'fun' correctly for both outer and inner functions. Others use invalid keywords or wrong order.
  3. Final Answer:

    fun outer() { fun inner() { println("Hi") } } -> Option A
  4. Quick Check:

    Local function syntax uses 'fun' keyword [OK]
Hint: Local functions use 'fun' keyword inside another function [OK]
Common Mistakes:
  • Using 'def' or 'function' instead of 'fun'
  • Placing 'fun' after the function call
  • Missing braces for function body
3. What will be the output of the following Kotlin code?
fun greet() {
    val prefix = "Hello"
    fun sayName(name: String) {
        println("$prefix, $name!")
    }
    sayName("Alice")
}
fun main() {
    greet()
}
medium
A. Hello, Alice!
B. Hello Alice!
C. Error: prefix not accessible
D. No output

Solution

  1. Step 1: Understand variable scope in local functions

    The local function 'sayName' can access 'prefix' from the outer function 'greet'.
  2. Step 2: Trace the output of sayName("Alice")

    It prints "Hello, Alice!" exactly as formatted with the comma and exclamation mark.
  3. Final Answer:

    Hello, Alice! -> Option A
  4. Quick Check:

    Local function accesses outer variable = Hello, Alice! [OK]
Hint: Local functions can use outer variables directly [OK]
Common Mistakes:
  • Assuming outer variables are inaccessible
  • Missing punctuation in output
  • Thinking code produces error
4. Identify the error in this Kotlin code snippet:
fun calculate() {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
}
fun main() {
    println(add(3, 4))
}
medium
A. Missing return type for 'add'
B. Syntax error in function declaration
C. Cannot call local function 'add' from outside 'calculate'
D. No error, prints 7

Solution

  1. Step 1: Understand local function visibility

    The function 'add' is local inside 'calculate' and cannot be accessed outside it.
  2. Step 2: Check where 'add' is called

    'add(3, 4)' is called in 'main', outside 'calculate', causing an error.
  3. Final Answer:

    Cannot call local function 'add' from outside 'calculate' -> Option C
  4. Quick Check:

    Local functions are private to outer function [OK]
Hint: Local functions can't be called outside their outer function [OK]
Common Mistakes:
  • Trying to call local function from outside
  • Confusing local and top-level functions
  • Ignoring function scope rules
5. You want to write a Kotlin function processNumbers that takes a list of integers and returns the sum of their squares. You decide to use a local function square inside it. Which of the following implementations correctly uses a local function to achieve this?
hard
A. fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x var sum = 0 for (n in nums) { sum += n } return sum }
B. fun processNumbers(nums: List<Int>): Int { var sum = 0 for (n in nums) { fun square(x: Int) = x * x sum += square } return sum }
C. fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.map square(it).sum() }
D. fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } }

Solution

  1. Step 1: Understand local function usage and Kotlin collection functions

    Local function 'square' should be declared once inside 'processNumbers'. Using Kotlin's 'sumOf' is concise and correct.
  2. Step 2: Analyze each option

    fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } correctly declares the local function once and uses it with sumOf { square(it) }.
    fun processNumbers(nums: List<Int>): Int { var sum = 0 for (n in nums) { fun square(x: Int) = x * x sum += square } return sum } declares 'square' inside the loop but calls it without argument square(n), compile error.
    fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.map square(it).sum() } has syntax error: nums.map square(it).sum() missing lambda braces {}.
    fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x var sum = 0 for (n in nums) { sum += n } return sum } defines 'square' but uses sum += n, computes sum of numbers not squares.
  3. Final Answer:

    fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } -> Option D
  4. Quick Check:

    Local function + sumOf = fun processNumbers(nums: List<Int>): Int { fun square(x: Int) = x * x return nums.sumOf { square(it) } } [OK]
Hint: Declare local function once; use sumOf for concise sum [OK]
Common Mistakes:
  • Calling local function without required arguments
  • Syntax error: missing braces in lambda expression
  • Defining local function but forgetting to use it
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard