Closures let you keep using variables from outside a function even after that function is created. This helps you write small, reusable pieces of code that remember important information.
0
0
Closures and variable capture in Kotlin
Introduction
When you want a function to remember a value from where it was made, like a counter.
When you need to pass a small function that uses some outside data to another function.
When you want to create a function that changes behavior based on some saved information.
When you want to keep some data private but still use it inside a function.
Syntax
Kotlin
val closure = { -> // code that uses variables from outside }
A closure is usually a lambda or anonymous function that uses variables from outside its own scope.
In Kotlin, lambdas automatically capture variables they use from the surrounding code.
Examples
This closure uses the variable
greeting from outside to greet a name.Kotlin
val greeting = "Hello" val sayHello = { name: String -> println("$greeting, $name!") } sayHello("Alice")
This function returns a closure that remembers and updates
count each time it is called.Kotlin
fun makeCounter(): () -> Int { var count = 0 return { ++count } } val counter = makeCounter() println(counter()) println(counter())
Sample Program
This program creates a closure that remembers the factor and multiplies any number by it.
Kotlin
fun makeMultiplier(factor: Int): (Int) -> Int { return { number -> number * factor } } fun main() { val multiplyBy3 = makeMultiplier(3) println(multiplyBy3(5)) println(multiplyBy3(10)) }
OutputSuccess
Important Notes
Closures capture variables by reference, so if the variable changes outside, the closure sees the new value.
Be careful with mutable variables inside closures to avoid unexpected results.
Summary
Closures are functions that remember variables from where they were created.
They help keep data private and create flexible, reusable code.
In Kotlin, lambdas automatically capture needed variables from outside.