0
0
Kotlinprogramming~10 mins

Closures and variable capture in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Closures and variable capture
Define outer function
Create inner function
Inner function captures outer variable
Return inner function
Call inner function later
Inner function uses captured variable
A closure is a function that remembers variables from its surrounding scope even after that scope has finished.
Execution Sample
Kotlin
fun makeCounter(): () -> Int {
    var count = 0
    return {
        count += 1
        count
    }
}

val counter = makeCounter()
println(counter())
println(counter())
This code creates a counter function that remembers and updates the count variable each time it is called.
Execution Table
StepActionVariable 'count'Returned ValueOutput
1Call makeCounter()count = 0 (initialized)Returns inner function
2Call counter() first timecount = 1 (incremented)1Prints 1
3Call counter() second timecount = 2 (incremented)2Prints 2
4No more callscount = 2 (final)Execution ends
💡 No more calls to counter(), so execution stops.
Variable Tracker
VariableStartAfter 1After 2Final
count0122
Key Moments - 2 Insights
Why does the inner function remember the variable 'count' even after makeCounter() finishes?
Because the inner function forms a closure that captures 'count' from its outer scope, keeping it alive as shown in execution_table steps 2 and 3.
What happens if we call makeCounter() again to create a new counter?
A new 'count' variable is created fresh for that new closure, independent from the first one, so counts do not mix.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' after the second call to counter()?
A2
B1
C0
D3
💡 Hint
Check the 'Variable count' column at Step 3 in the execution_table.
At which step does the inner function first increment 'count'?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Variable count' columns in execution_table for when count changes from 0 to 1.
If we create a second counter by calling makeCounter() again, what will be the initial value of 'count' for it?
A1
B0
C2
DUndefined
💡 Hint
Recall that each call to makeCounter() initializes 'count' to 0 as in Step 1.
Concept Snapshot
Closures capture variables from their outer scope.
In Kotlin, inner functions can access and modify these variables.
Captured variables live as long as the closure.
Each closure has its own copy of captured variables.
Use closures to keep state between calls.
Full Transcript
This example shows how a Kotlin function makeCounter returns another function that remembers a variable 'count'. When makeCounter is called, it sets count to 0 and returns an inner function. This inner function increases count by 1 each time it is called and returns the new count. The variable 'count' is captured by the closure, so it stays alive even after makeCounter finishes. Calling counter() twice shows count increasing from 0 to 1, then 2. This demonstrates how closures keep variables alive and allow functions to remember state.