Kotlin Tip #9: Utilize Higher-Order Functions — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readFeb 18, 2024

Twitter | LinkedIn | YouTube | Instagram
Tip #8:
Embrace Single Expression Functions

In mathematics, functions that operate on other functions are a well-established concept, often seen in calculus and functional analysis. These operations are known in software development as high-order functions, a concept that is deeply rooted in functional programming and that allows developers to write more flexible, abstract, and reusable code.

Higher-order functions are functions that can take functions as parameters and/or return a function. This capability to use functions as values opens up a wide options of programming patterns and techniques that can make code more declarative, meaning you focus on what to do rather than how to do it.

Let’s take a look at the example below. In this example, calculate is a higher-order function. It takes three parameters, two integers (a and b), and a function (operation).

fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int) = operation(a, b)

The parameter operation is also a function that, in turn, takes two integers and returns another integer. Then, the calculate function applies the operation function to a and b, and returns the result.

We then use calculate with two different functions: one that adds its arguments and one that subtracts its arguments. This demonstrates how higher-order functions can be used to create more flexible and reusable code.

Another example is implementing a higher-order function for measuring how long a function takes to be processed. I particularly like this use case because it helps us encapsulate the logic for calculating the time spent in a function and reuse it whenever needed. Let’s see how we can implement it with higher-order functions.

In this example, longRunningOperation() is a function that simulates a long-running operation by sleeping for 2 seconds.

We pass this function to measureTime() using the :: operator. measureTime() then runs the operation, measures the time before and after, and logs the elapsed time. This demonstrates how higher-order functions can be used to add behavior (in this case, logging) to other functions.

I hope you have enjoyed the ninth tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #10: Prefer Immutable Collections

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--