Search⌘ K
AI Features

Functions as Values

Learn how to use functions as first-class values in Kotlin by exploring higher-order functions, anonymous and lambda functions, and function references. Understand how these concepts support functional programming principles and improve code reuse and readability.

The Strategy and Command design patterns are only two examples that rely heavily on the ability to accept functions as arguments, return functions, store functions as values, or put functions inside of collections.

Learning about higher-order functions

In Kotlin, it’s possible for a function to return another function. Let’s look at the following simple function to understand this syntax in depth:

fun generateMultiply(): (Int) -> Int {
return fun(x: Int): Int {
return x * 2
}
}
A function that returns a lambda expression that multiplies its argument by 2

Here, our generateMultiply function returns another function that doesn’t have a name. Functions without a name are called anonymous functions. We could also rewrite the preceding code using shorter syntax:

fun generateMultiply(): (Int) -> Int {
return { x: Int ->
x * 2
}
}
Returns a lambda function that multiplies its input by 2

If a function without a name uses short syntax, it’s called a lambda function.

Next, let’s look at the signature of the return ...