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.
We'll cover the following...
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}}
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}}
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 ...