Search⌘ K
AI Features

Closures and Pure Functions

Explore closures and pure functions in Kotlin to understand how functions can encapsulate state and avoid side effects. Learn how pure functions improve testability, predictability, and maintainability by eliminating external dependencies and side effects. This lesson helps you apply functional programming principles to write cleaner, more reliable Kotlin code.

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 = 0
return { 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:

Kotlin 1.5
fun main() {
fun counter(): () -> Int {
var i = 0
return { 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 reference ...