0
0
Kotlinprogramming~5 mins

Closures and variable capture in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AOnly function names
BVariables and their current values
COnly immutable variables
DNothing, closures have no access to outside variables
If a variable captured by a Kotlin closure changes after the closure is created, what value does the closure see?
AThe updated value
BThe original value at capture time
CNull
DAn error occurs
Which keyword in Kotlin declares a mutable variable that can be captured and modified by a closure?
Avar
Bval
Cfun
Dconst
What will the following Kotlin code print? var x = 5 val f = { x += 10 } f() println(x)
AError
B5
C10
D15
Why are closures important in asynchronous programming?
AThey run code faster
BThey prevent any variable changes
CThey keep state and access variables even after the outer function ends
DThey block the main thread
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.