0
0
Kotlinprogramming~20 mins

Closures and variable capture in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of closure capturing a loop variable
What is the output of this Kotlin code snippet?
Kotlin
fun main() {
    val funcs = mutableListOf<() -> Int>()
    for (i in 1..3) {
        funcs.add { i * 2 }
    }
    funcs.forEach { println(it()) }
}
A
2
4
6
B
6
6
6
C
2
2
2
D
1
2
3
Attempts:
2 left
💡 Hint
Remember that each lambda captures the current value of i in the loop.
Predict Output
intermediate
2:00remaining
Closure capturing mutable variable
What will be printed by this Kotlin program?
Kotlin
fun main() {
    var x = 5
    val f = { x += 1; x }
    println(f())
    println(f())
}
A
6
7
B
5
6
C
7
8
D
6
6
Attempts:
2 left
💡 Hint
The lambda modifies the variable x each time it is called.
🔧 Debug
advanced
2:30remaining
Why does this closure capture unexpected value?
This Kotlin code prints the same number three times instead of 1, 2, 3. Why?
Kotlin
fun main() {
    val funcs = mutableListOf<() -> Int>()
    var i = 1
    while (i <= 3) {
        funcs.add { i }
        i++
    }
    funcs.forEach { println(it()) }
}
AThe variable i is captured by reference, so all lambdas see the final value 4.
BThe lambdas capture a copy of i at each iteration, so output should be 1, 2, 3.
CThe while loop does not increment i correctly, causing infinite loop.
DThe list funcs is empty, so nothing is printed.
Attempts:
2 left
💡 Hint
Think about how the variable i is shared among all lambdas.
Predict Output
advanced
2:00remaining
Output of nested closures with variable shadowing
What is the output of this Kotlin code?
Kotlin
fun main() {
    var x = 10
    val f = {
        val x = 5
        {
            x
        }
    }
    val g = f()
    println(g())
}
A10
B0
CCompilation error due to shadowing
D5
Attempts:
2 left
💡 Hint
Inner lambda captures the closest x in scope.
🧠 Conceptual
expert
3:00remaining
Why does Kotlin capture variables by reference in closures?
Which is the main reason Kotlin closures capture variables by reference rather than by value?
ABecause Kotlin does not support capturing variables in closures.
BTo improve performance by copying variables each time the lambda is called.
CTo allow lambdas to modify the original variable and reflect changes across calls.
DTo prevent any changes to the variable after the lambda is created.
Attempts:
2 left
💡 Hint
Think about how closures can change variables outside their scope.