0
0
Kotlinprogramming~3 mins

Why Returning functions from functions in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one function could hand you another function ready to solve your problem instantly?

The Scenario

Imagine you want to create different calculators for adding, subtracting, or multiplying numbers. Without returning functions, you'd have to write separate code for each calculator and call them manually every time.

The Problem

This manual way means repeating similar code again and again. It's slow to write, easy to make mistakes, and hard to change later if you want a new calculator type.

The Solution

By returning functions from functions, you can create a flexible calculator maker. One function can give you back the exact calculator you want, ready to use. This saves time, reduces errors, and makes your code neat and easy to update.

Before vs After
Before
fun add(a: Int, b: Int) = a + b
fun subtract(a: Int, b: Int) = a - b
// Call add(5,3) or subtract(5,3) manually
After
fun getCalculator(op: String): (Int, Int) -> Int = when(op) {
  "add" -> { a, b -> a + b }
  "subtract" -> { a, b -> a - b }
  else -> { _, _ -> 0 }
}
// val calc = getCalculator("add")
// calc(5,3)
What It Enables

This lets you build smart, reusable tools that create other tools on demand, making your programs powerful and flexible.

Real Life Example

Think of a coffee machine that can make espresso, latte, or cappuccino. Instead of building a new machine for each, you have one machine that returns the right coffee maker function based on your choice.

Key Takeaways

Manual repetition is slow and error-prone.

Returning functions creates flexible, reusable code.

It helps build smart tools that adapt to different needs.