🧮 Kotlin Functions – Declarations, Lambdas, Higher-Order Logic & Recursion
🧲 Introduction – Write Modular, Reusable Logic with Kotlin Functions
Functions are the backbone of Kotlin programs. They enable code reuse, logical organization, and abstraction. Kotlin extends basic function declarations with default arguments, lambda expressions, higher-order functions, inline functions, and recursion—providing powerful tools for building clean and concise logic.
🎯 In this guide, you’ll learn:
- How to declare Kotlin functions with parameters and return types
- How to use default arguments and single-expression functions
- How to write and use lambdas and anonymous functions
- What higher-order functions and inline functions are
- How recursion works in Kotlin with examples
📘 Topics Covered
| 🔍 Topic | 📖 Description |
|---|---|
| 🧾 Kotlin – Functions | How to define and call functions with parameters and return types. |
| 🧮 Kotlin – Lambda Expressions | Creating anonymous functions for cleaner, inline logic. |
| 🔄 Kotlin – Higher-Order Functions | Passing functions as parameters or returning them as values. |
| ⚡ Kotlin – Inline Functions | Using inline to optimize performance by avoiding function object allocation. |
| ♻️ Kotlin – Recursion | Calling functions from themselves to solve repetitive problems. |
🔍 Detailed Sections & Examples
🧾 Kotlin – Functions (Declaration, Return Types, Default Arguments)
fun greet(name: String = "User"): String {
return "Hello, $name!"
}
fun main() {
println(greet()) // Output: Hello, User!
println(greet("Vaibhav")) // Output: Hello, Vaibhav!
}
🧠 Explanation:
fundeclares a function.- Parameters can have default values.
- Functions can return values or be
Unit(likevoidin Java).
✅ Single-expression Function:
fun square(n: Int) = n * n
🧮 Kotlin – Lambda Expressions
val sum = { a: Int, b: Int -> a + b }
println(sum(5, 10)) // Output: 15
🧠 Explanation:
- Lambdas are unnamed functions.
- Syntax:
{ parameters -> result } - Often used with collection functions (
map,filter,forEach).
✅ Example with forEach:
val list = listOf("Kotlin", "Java", "Swift")
list.forEach { println(it) }
🔄 Kotlin – Higher-Order Functions
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val result = calculate(5, 3) { x, y -> x * y }
println(result) // Output: 15
💡 A function that accepts another function as a parameter is a higher-order function.
⚡ Kotlin – Inline Functions
inline fun log(block: () -> Unit) {
println("Log Start")
block()
println("Log End")
}
log {
println("Processing...")
}
🧠 Inline functions replace the call with the actual function body during compilation, reducing runtime overhead—especially beneficial in high-order functions.
♻️ Kotlin – Recursion
fun factorial(n: Int): Int {
return if (n == 1) 1 else n * factorial(n - 1)
}
println(factorial(5)) // Output: 120
📌 Recursion allows a function to call itself—great for problems like factorial, Fibonacci, etc.
✅ Tail Recursion Optimization:
tailrec fun sum(n: Int, acc: Int = 0): Int {
return if (n == 0) acc else sum(n - 1, acc + n)
}
Use tailrec for compiler optimization.
📌 Summary – Recap & Next Steps
Kotlin functions allow you to build modular, flexible, and performant code structures. With support for lambdas, higher-order design, inline efficiency, and recursion, Kotlin goes far beyond traditional procedural styles.
🔍 Key Takeaways:
- Define reusable logic using
fun, with optional return types and defaults. - Use lambda expressions for inline logic and callback-style code.
- Higher-order functions boost abstraction and functional style.
- Inline functions reduce overhead and improve performance.
- Recursion helps in solving divide-and-conquer or repetitive problems.
⚙️ Practical Use Cases:
- Abstracting repeated business logic
- Passing functions for callbacks (like click listeners)
- Optimizing performance in functional collections
- Solving recursive problems like tree traversal, sorting
❓ Frequently Asked Questions
❓ What’s the difference between a function and a lambda in Kotlin?
✅ Functions have names and can be reused globally. Lambdas are anonymous functions often passed as arguments or stored in variables.
❓ Can I return a function in Kotlin?
✅ Yes. Kotlin supports returning functions from other functions.
fun multiplyBy(factor: Int): (Int) -> Int {
return { it * factor }
}
❓ What is the purpose of inline functions?
✅ To improve performance by avoiding lambda object creation at runtime. Ideal for higher-order functions.
❓ How does tail recursion differ from regular recursion?
✅ Tail recursion performs optimization where the recursive call is the last operation—Kotlin replaces it with a loop internally.
❓ Are default parameters better than function overloading?
✅ Yes. Kotlin favors default parameters and named arguments over traditional overloads, making code cleaner.
Share Now :
