🧠 Kotlin – Higher-Order Functions: Functions That Accept Functions
🧲 Introduction – Why Learn Kotlin Higher-Order Functions?
Higher-order functions (HOFs) are a core concept in functional programming, and Kotlin embraces them fully. These are functions that can accept other functions as parameters or return functions as results. HOFs allow you to write more flexible, modular, and reusable code, especially useful for callbacks, collections, and DSLs.
🎯 In this guide, you’ll learn:
- What higher-order functions are in Kotlin
- How to pass lambdas or function references as arguments
- How to return functions from functions
- Real-world examples using
map
,filter
,run
,let
, etc.
🧾 What Is a Higher-Order Function?
A higher-order function is a function that:
- Takes one or more functions as arguments, or
- Returns a function as a result.
✅ Basic Example:
fun operate(a: Int, b: Int, action: (Int, Int) -> Int): Int {
return action(a, b)
}
val sum = operate(4, 5) { x, y -> x + y }
println("Result: $sum")
🟢 Output:
Result: 9
action
is a lambda(Int, Int) -> Int
- Passed directly during function call
🔁 Returning a Function from Another Function
fun multiplier(factor: Int): (Int) -> Int {
return { number -> number * factor }
}
val double = multiplier(2)
println(double(4)) // Output: 8
✔️ The outer function returns a lambda that multiplies by a given factor.
🧰 Built-in Higher-Order Functions in Kotlin
🔹 map
val nums = listOf(1, 2, 3)
val squares = nums.map { it * it }
println(squares) // [1, 4, 9]
🔹 filter
val evens = nums.filter { it % 2 == 0 }
println(evens) // [2]
🔹 forEach
nums.forEach { println("Item: $it") }
🔧 Inline Functions for Performance
You can mark HOFs as inline
to avoid the performance cost of creating extra function objects and classes:
inline fun applyOp(a: Int, b: Int, op: (Int, Int) -> Int): Int {
return op(a, b)
}
✅ Great for tight loops or lambdas that are performance-critical.
🧠 Function Types & Type Aliases
You can simplify complex function signatures using type aliases:
typealias MathOp = (Int, Int) -> Int
fun calculate(a: Int, b: Int, op: MathOp): Int = op(a, b)
✔️ Improves readability for multiple higher-order calls.
🧩 Real-World Use: Event Callback
fun registerCallback(onClick: () -> Unit) {
println("Registering...")
onClick()
}
registerCallback { println("Button clicked!") }
✅ Perfect for UI events, listeners, and coroutine builders.
🚫 Common Mistakes
❌ Mistake | ✅ Fix |
---|---|
Forgetting parentheses for function calls | Always invoke functions when passing result |
Passing Unit instead of lambda | Pass lambda, not result of a function |
Overcomplicating inline lambdas | Keep expressions simple or extract to named lambdas |
✅ Best Practices for Higher-Order Functions
Practice | Why It Helps |
---|---|
Use inline for small, performance-critical lambdas | Reduces runtime overhead |
Use function types or aliases | Improves code readability |
Prefer lambdas over anonymous functions | Cleaner and more idiomatic Kotlin |
Use trailing lambda syntax when applicable | Improves readability |
📌 Summary – Recap & Next Steps
Kotlin’s higher-order functions allow you to treat functions as first-class citizens, making your code more abstract, modular, and expressive. They power everything from collection operations to callback systems and Kotlin DSLs.
🔍 Key Takeaways:
- Higher-order functions can take or return functions.
- Lambdas are commonly used as arguments.
- Built-in functions like
map
,filter
, andforEach
rely on HOFs. - Use
inline
for performance-sensitive operations.
⚙️ Practical Use:
HOFs shine in event-driven programming, collections processing, custom logic injections, and Android click listeners.
❓ FAQs – Kotlin Higher-Order Functions
❓ What is a higher-order function in Kotlin?
✅ A function that takes another function as a parameter or returns one.
❓ How do I pass a lambda to a Kotlin function?
✅ Use a lambda as an argument:
fun greet(action: () -> Unit) = action()
greet { println("Hi!") }
❓ Can functions return other functions in Kotlin?
✅ Yes:
fun getMultiplier(x: Int): (Int) -> Int = { it * x }
❓ Why use inline
with higher-order functions?
✅ To avoid runtime overhead from lambda object creation and enable optimizations.
❓ What are function types in Kotlin?
✅ Function types like (Int, String) -> Boolean
define functions that accept an Int
, a String
, and return a Boolean
.
Share Now :