Discover how one simple change can make your functions cleaner and your code happier!
Why Single-expression functions in Kotlin? - Purpose & Use Cases
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.
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.
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.
fun add(a: Int, b: Int): Int {
return a + b
}fun add(a: Int, b: Int) = a + b
It enables writing clear and concise functions that are easy to read and maintain, making your code more elegant and less error-prone.
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.
Manual functions can be long and cluttered.
Single-expression functions simplify code to one line.
This makes code easier to read and write.