Search⌘ K
AI Features

Currying and Memoization

Explore currying to transform multi-argument functions into chains of single-argument functions for flexible code use. Understand memoization to cache pure function results and reduce redundant computations. These techniques leverage Kotlin's functional features to help you write efficient, reusable code.

We'll cover the following...

Currying

Currying is a way to translate a function that takes a number of arguments into a chain of functions, where each function takes a single argument. This may sound confusing, so let’s look at a simple example:

fun subtract(x: Int, y: Int): Int {
return x - y
}
println(subtract(50, 8))
Subtract function

This is a function that takes two arguments as an input and returns the difference between them. However, some languages allow us to invoke this function with the following syntax:

subtract(50)(8)

This is what currying looks like. Currying allows us to take a function with multiple arguments (in our case, two) and convert this function into a set of functions, where each one takes only a single argument.

Let’s examine how this can be achieved in Kotlin. We’ve already seen how we can return a function from another function:

fun subtract(x: Int): (Int) -> Int {
return fun(y: Int): Int {
return x - y
}
}
Returns a lambda function that takes an integer y as input and returns the result of subtracting x from y

Here is the shorter form of the preceding code:

fun subtract(x: Int) = fun(y: Int): Int {
return x - y
}
Returns a function that subtracts a given number from its argument

In the preceding example, we ...