Closures in Kotlin
Kotlin supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
When you run this program, you’ll see:
In this Kotlin example, we’ve created a closure using an anonymous function. The intSeq
function returns another function that increments and returns a counter. Each time we call intSeq()
, it creates a new instance of the anonymous function with its own i
variable.
The nextInt
variable holds a reference to the anonymous function returned by intSeq()
. Each time we call nextInt()
, it increments its own i
and returns the new value.
We create a second closure newInts
to demonstrate that each closure maintains its own independent state.
Closures are a powerful feature in Kotlin, allowing you to create functions with persistent, private state. They’re commonly used in functional programming patterns and can be very useful for creating iterators, callbacks, and other stateful functions.
The next feature of functions we’ll look at is recursion.