Bird
Raised Fist0
Kotlinprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does a closure in Kotlin do with variables from its surrounding scope?
easy
A. It copies the variables but cannot modify them.
B. It deletes those variables to save memory.
C. It ignores variables outside its own body.
D. It remembers and can use those variables even after the outer function ends.

Solution

  1. Step 1: Understand closure behavior

    A closure is a function that keeps access to variables from where it was created, even if that place no longer exists.
  2. Step 2: Apply to Kotlin closures

    In Kotlin, lambdas capture variables from the surrounding scope and can use them later.
  3. Final Answer:

    It remembers and can use those variables even after the outer function ends. -> Option D
  4. Quick Check:

    Closure remembers and can use variables even after outer ends = C [OK]
Hint: Closures keep variables alive beyond their original scope [OK]
Common Mistakes:
  • Thinking closures delete outside variables
  • Believing closures only copy variables without access
  • Assuming closures ignore outside variables
2. Which of the following is the correct syntax to create a lambda that captures a variable count in Kotlin?
easy
A. val lambda = (count) -> println(count)
B. val lambda = { println(count) }
C. val lambda = fun(count) { println(count) }
D. val lambda = { count -> println() }

Solution

  1. Step 1: Identify lambda syntax capturing external variable

    In Kotlin, a lambda can access variables from outside without parameters by just using them inside curly braces.
  2. Step 2: Check each option

    val lambda = { println(count) } correctly uses count from outside. val lambda = (count) -> println(count) tries to declare a parameter but syntax is wrong. val lambda = fun(count) { println(count) } uses fun keyword incorrectly. val lambda = { count -> println() } declares a parameter but does not use it properly.
  3. Final Answer:

    val lambda = { println(count) } -> Option B
  4. Quick Check:

    Lambda uses outside variable directly = A [OK]
Hint: Use curly braces and refer to outside variables directly [OK]
Common Mistakes:
  • Trying to declare external variables as lambda parameters
  • Using incorrect lambda syntax with fun keyword
  • Not referencing the variable inside the lambda body
3. What will be the output of the following Kotlin code?
fun main() {
    var x = 5
    val closure = { x += 1; println(x) }
    closure()
    closure()
    println(x)
}
medium
A. 6\n7\n7
B. 6\n6\n5
C. 6\n7\n5
D. 5\n5\n5

Solution

  1. Step 1: Trace the closure calls and variable changes

    Initially, x = 5. First closure call increments x to 6 and prints 6. Second call increments x to 7 and prints 7.
  2. Step 2: Print final value of x

    After two increments, x is 7, so printing x outputs 7.
  3. Final Answer:

    6\n7\n7 -> Option A
  4. Quick Check:

    Closure increments x twice, final x = 7 [OK]
Hint: Closures can modify captured vars; track changes stepwise [OK]
Common Mistakes:
  • Assuming closure uses a copy of x, not the original
  • Forgetting x increments on each closure call
  • Confusing printed values with initial x
4. Identify the error in this Kotlin code that tries to capture a variable inside a loop:
fun main() {
    val funcs = mutableListOf<() -> Unit>()
    for (i in 1..3) {
        funcs.add { println(i) }
    }
    funcs.forEach { it() }
}
medium
A. All lambdas print 3 instead of 1, 2, 3
B. Runtime error: variable i not found
C. Lambdas print 1, 2, 3 correctly
D. Syntax error: cannot capture loop variable

Solution

  1. Step 1: Understand variable capture in Kotlin loops

    Kotlin captures the loop variable i correctly for each lambda, so each lambda remembers its own i value.
  2. Step 2: Check output of lambdas

    When calling each lambda, they print 1, 2, and 3 respectively, no error occurs.
  3. Final Answer:

    Lambdas print 1, 2, 3 correctly -> Option C
  4. Quick Check:

    Kotlin captures loop vars per iteration = B [OK]
Hint: Kotlin captures loop vars freshly each iteration [OK]
Common Mistakes:
  • Assuming all lambdas print the last loop value
  • Expecting syntax or runtime errors for capturing loop vars
  • Confusing Kotlin behavior with other languages like JavaScript
5. You want to create a list of functions in Kotlin, each printing a different number from 1 to 3. Which code correctly captures the variable to avoid all functions printing the same number?
val funcs = mutableListOf<() -> Unit>()
for (i in 1..3) {
    // What to do here?
}
funcs.forEach { it() }
hard
A. for (i in 1..3) { funcs.add { println(i) } }
B. for (i in 1..3) { val x = i + 1; funcs.add { println(x) } }
C. for (i in 1..3) { funcs.add { println(i + 1) } }
D. for (i in 1..3) { val x = i; funcs.add { println(x + 1) } }

Solution

  1. Step 1: Understand variable capture in Kotlin for loops

    In Kotlin, lambdas added inside a for (i in 1..3) capture the i from their iteration correctly.
  2. Step 2: Check each snippet

    funcs.add { println(i) } prints 1 then 2 then 3. The snippet with val x = i + 1; funcs.add { println(x) } prints 2 3 4. funcs.add { println(i + 1) } prints 2 3 4. val x = i; funcs.add { println(x + 1) } prints 2 3 4.
  3. Final Answer:

    for (i in 1..3) { funcs.add { println(i) } } -> Option A
  4. Quick Check:

    Direct println(i) in for loop lambda = B [OK]
Hint: Directly use loop var i inside lambda [OK]
Common Mistakes:
  • Declaring x = i + 1 and printing x (prints 2 3 4)
  • Printing i + 1 directly (prints 2 3 4)
  • Copying to x = i but printing x + 1 (prints 2 3 4)
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