Closures and Pure Functions
Learn about closures and pure functions in Kotlin.
We'll cover the following...
In the object-oriented paradigm, state is always stored within objects. But in functional programming, this isn’t necessarily the case. Let’s look at the following function as an example:
fun counter(): () -> Int {var i = 0return { i++ }}
A function returns a lambda that counts up each time it's called
The preceding example is clearly a higher-order function, as we can see by its return type. It returns a function with zero arguments that produces an integer.
Let’s store it in a variable, and invoke it multiple times:
Press + to interact
fun main() {fun counter(): () -> Int {var i = 0return { i++ }}val next = counter()println(next())println(next())println(next())}
As we can see, the function is able to keep a state, in this case, the value of a counter, even though it is not part of an object.
This is called a closure. The lambda has access to all of the local variables of the function that wraps it, and those local variables persist, as long as the ...