0
0
Kotlinprogramming~3 mins

Why Single-expression functions in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one simple change can make your functions cleaner and your code happier!

The Scenario

Imagine you want to write a simple function that adds two numbers. You write multiple lines with curly braces and return statements every time. It feels like writing a whole paragraph just to say one thing.

The Problem

This long way is slow to write and read. It clutters your code with extra words and braces. When you want to see what the function does, you have to scroll through unnecessary lines. It's easy to make mistakes or miss the main point.

The Solution

Single-expression functions let you write that same function in one clean line. You just write the function name, parameters, and the expression it returns. No braces, no return keyword. It makes your code shorter, clearer, and easier to understand.

Before vs After
Before
fun add(a: Int, b: Int): Int {
    return a + b
}
After
fun add(a: Int, b: Int) = a + b
What It Enables

It enables writing clear and concise functions that are easy to read and maintain, making your code more elegant and less error-prone.

Real Life Example

When creating small helper functions like calculating a discount or formatting a string, single-expression functions let you write them quickly and keep your code neat.

Key Takeaways

Manual functions can be long and cluttered.

Single-expression functions simplify code to one line.

This makes code easier to read and write.