Kotlin Higher-Order Functions: Functions That Take Functions! 🚀
Imagine you’re at a coffee shop ☕, and the barista asks:
"How would you like your coffee?"
You can choose:
✅ Black Coffee ☕
✅ With Sugar 🍬
✅ With Milk 🥛
✅ Both Sugar & Milk 🍶
The coffee-making process remains the same, but you pass a custom instruction (how you want it).
That’s exactly how higher-order functions work in Kotlin!
📌 In this blog, we’ll explore:
✅ What are Higher-Order Functions? 🤔
✅ Passing Functions as Parameters 🔄
✅ Returning Functions from Functions 🚀
✅ Using Lambda Expressions for Simplicity ✨
✅ Real-World Examples 🌍
1️⃣ What is a Higher-Order Function? 🤔
A higher-order function is a function that takes another function as a parameter or returns a function.
📌 Why is this useful?
- Helps in writing cleaner, reusable, and modular code.
- Allows dynamic behavior (just like ordering custom coffee ☕).
- Used in functional programming to process collections efficiently.
2️⃣ Passing Functions as Parameters 🔄
We can pass one function as an argument to another function!
🔹 Example: Performing a Math Operation
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b) // Calls the passed function
}
// Different operations
val add = { x: Int, y: Int -> x + y }
val multiply = { x: Int, y: Int -> x * y }
// Using higher-order function
println(calculate(5, 3, add)) // Output: 8
println(calculate(5, 3, multiply)) // Output: 15
📌 Here’s what happens:
calculate(5, 3, add)
callsadd(5, 3)
, which returns8
.calculate(5, 3, multiply)
callsmultiply(5, 3)
, which returns15
.
✅ Same function, different behaviors!
3️⃣ Returning a Function from a Function 🚀
A higher-order function can also return another function.
🔹 Example: Getting a Discount Function
fun getDiscountFunction(type: String): (Double) -> Double {
return when (type) {
"student" -> { price -> price * 0.9 } // 10% off
"senior" -> { price -> price * 0.85 } // 15% off
else -> { price -> price } // No discount
}
}
val studentDiscount = getDiscountFunction("student")
println(studentDiscount(100.0)) // Output: 90.0
val seniorDiscount = getDiscountFunction("senior")
println(seniorDiscount(100.0)) // Output: 85.0
📌 Explanation:
- The function returns another function based on the discount type.
- We store the function in
studentDiscount
orseniorDiscount
. - Calling
studentDiscount(100.0)
applies a 10% discount.
✅ Dynamic pricing logic with functions!
4️⃣ Using Lambda Expressions for Simplicity ✨
Instead of writing long function definitions, we can use lambda expressions for shorter, cleaner code.
🔹 Example: Sorting a List with a Lambda
val numbers = listOf(3, 1, 4, 2)
val sortedNumbers = numbers.sortedBy { it } // Lambda for sorting
println(sortedNumbers) // Output: [1, 2, 3, 4]
📌 Instead of defining a separate function, we use { it }
as a quick function.
✅ Less code, same power!
5️⃣ Real-World Use Cases 🌍
🔹 1. Filtering a List
val words = listOf("Kotlin", "Java", "C++", "Python")
val longWords = words.filter { it.length > 4 }
println(longWords) // Output: [Kotlin, Python]
✅ Higher-order functions like filter
simplify list processing!
🔹 2. Mapping Values in a List
val numbers = listOf(1, 2, 3, 4)
val squaredNumbers = numbers.map { it * it }
println(squaredNumbers) // Output: [1, 4, 9, 16]
✅ Easier than writing a loop!
🔹 3. Custom Sorting with Higher-Order Functions
val names = listOf("John", "Alice", "Bob")
val sortedByLength = names.sortedBy { it.length }
println(sortedByLength) // Output: [Bob, John, Alice]
✅ Higher-order functions help in sorting based on custom logic!
🔟 Conclusion: Functions Inside Functions! 🎯
✅ Higher-order functions allow us to pass and return functions.
✅ Lambdas make code cleaner and more readable.
✅ They are widely used in list processing, sorting, filtering, and more.
✅ They help in writing modular, reusable, and dynamic code.
Now go ahead and experiment with Kotlin higher-order functions in your projects! 🚀
💬 Which part did you like the most? Let me know in the comments! ⬇️😊