Challenge - 5 Problems
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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()) } }
Attempts:
2 left
💡 Hint
Remember that each lambda captures the current value of i in the loop.
✗ Incorrect
Each lambda captures the current value of i during each iteration. So the outputs are 2, 4, and 6 respectively.
❓ Predict Output
intermediate2: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()) }
Attempts:
2 left
💡 Hint
The lambda modifies the variable x each time it is called.
✗ Incorrect
The lambda increments x by 1 each time it runs, so first it prints 6, then 7.
🔧 Debug
advanced2: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()) } }
Attempts:
2 left
💡 Hint
Think about how the variable i is shared among all lambdas.
✗ Incorrect
All lambdas capture the same variable i by reference. After the loop ends, i is 4, so all lambdas print 4.
❓ Predict Output
advanced2: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()) }
Attempts:
2 left
💡 Hint
Inner lambda captures the closest x in scope.
✗ Incorrect
The inner lambda captures the x declared inside f, which is 5, shadowing the outer x.
🧠 Conceptual
expert3: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?
Attempts:
2 left
💡 Hint
Think about how closures can change variables outside their scope.
✗ Incorrect
Kotlin captures variables by reference so that lambdas can modify and share the same variable state.