0
0
Kotlinprogramming~10 mins

Returning functions from functions in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Returning functions from functions
Call outerFunction
outerFunction runs
Create innerFunction
Return innerFunction
Call returned innerFunction
innerFunction runs and returns result
The outer function creates and returns an inner function. Later, calling the returned function runs the inner function's code.
Execution Sample
Kotlin
fun outerFunction(): (Int) -> Int {
    return fun(x: Int): Int { return x * 2 }
}

val f = outerFunction()
println(f(5))
Defines a function that returns another function doubling its input, then calls it with 5.
Execution Table
StepActionEvaluationResult
1Call outerFunction()Runs outerFunction bodyReturns inner function (x) -> x * 2
2Assign returned function to ff now holds inner functionf = (x) -> x * 2
3Call f(5)Runs inner function with x=5Returns 10
4Print resultOutput value10
💡 Execution stops after printing the result of f(5)
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
fundefinedfunction returned by outerFunctionfunction assignedfunction called with 5function remains assigned
Key Moments - 3 Insights
Why does outerFunction return a function instead of a value?
Because outerFunction's return type is a function type (Int) -> Int, it returns a function object, as shown in execution_table step 1.
How do we call the function returned by outerFunction?
We assign it to a variable (f) and then call f with an argument, as shown in execution_table steps 2 and 3.
What happens when we call f(5)?
The inner function runs with x=5 and returns 10, as shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of calling f(5)?
AFunction object
B10
C5
DError
💡 Hint
Check execution_table row 3 where f(5) is called and returns 10.
At which step is the inner function created and returned?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at execution_table step 1 where outerFunction returns the inner function.
If we change outerFunction to return a function that triples x, what would f(5) return?
A15
B10
C5
DError
💡 Hint
Think about the inner function's return value when multiplying x by 3 instead of 2.
Concept Snapshot
fun outerFunction(): (Int) -> Int {
  return fun(x: Int): Int { return x * 2 }
}

val f = outerFunction()  // f is a function
println(f(5))           // prints 10

- Functions can return other functions.
- Returned functions can be called later.
Full Transcript
This example shows how a Kotlin function can return another function. The outerFunction returns an inner function that doubles its input. When we call outerFunction, it returns this inner function, which we store in variable f. Calling f(5) runs the inner function with 5, returning 10. This lets us create functions dynamically and use them later.