Currying and Memoization
Learn about currying and memoization in Kotlin.
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))
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}}
Here is the ...