Recall & Review
beginner
What is a closure in Kotlin?
A closure is a function that captures variables from its surrounding scope and can use them even after that scope has ended.
Click to reveal answer
intermediate
How does Kotlin handle variable capture in closures?
Kotlin captures variables by reference, so if the variable changes after the closure is created, the closure sees the updated value.
Click to reveal answer
intermediate
What happens if you modify a captured variable inside a Kotlin closure?
If the variable is mutable (like a var), the closure can modify it, and changes will be visible outside the closure as well.
Click to reveal answer
beginner
Explain variable capture with an example in Kotlin.
Example:
var count = 0
val increment = { count += 1 }
increment()
println(count) // prints 1
Here, the closure 'increment' captures 'count' and modifies it.
Click to reveal answer
beginner
Why are closures useful in Kotlin programming?
Closures let you write flexible code by keeping state inside functions, enabling callbacks, and simplifying asynchronous or event-driven programming.Click to reveal answer
In Kotlin, what does a closure capture from its surrounding scope?
✗ Incorrect
Closures capture variables from their surrounding scope, including their current values.
If a variable captured by a Kotlin closure changes after the closure is created, what value does the closure see?
✗ Incorrect
Kotlin captures variables by reference, so the closure sees the updated value.
Which keyword in Kotlin declares a mutable variable that can be captured and modified by a closure?
✗ Incorrect
'var' declares a mutable variable that closures can modify.
What will the following Kotlin code print?
var x = 5
val f = { x += 10 }
f()
println(x)
✗ Incorrect
The closure modifies 'x' by adding 10, so x becomes 15.
Why are closures important in asynchronous programming?
✗ Incorrect
Closures keep state and access variables after the outer function ends, which is useful in async code.
Describe what a closure is and how Kotlin captures variables inside it.
Think about how a function can remember variables from outside its own body.
You got /3 concepts.
Explain with an example how modifying a captured variable inside a Kotlin closure affects the variable outside the closure.
Use a simple var variable and a lambda that changes it.
You got /3 concepts.