Single Expression Function in Kotlin: Simple and Clear Explanation
single expression function in Kotlin is a function that returns the result of a single expression without using curly braces or the return keyword. It simplifies code by writing the function body directly after an equals sign =.How It Works
Think of a single expression function like a quick answer to a question. Instead of writing a full explanation, you just give the final result right away. In Kotlin, this means you write the function with an equals sign = followed by the expression that produces the result.
This is like saying, "To get the answer, just do this one thing." The function automatically returns the value of that expression without needing extra words like return or curly braces {}. It makes your code shorter and easier to read, especially when the function is simple.
Example
This example shows a single expression function that adds two numbers and returns the sum.
fun add(a: Int, b: Int): Int = a + b
fun main() {
println(add(5, 3))
}When to Use
Use single expression functions when your function can be written as one simple expression. This is common for small calculations, returning a value directly, or calling another function. It helps keep your code clean and concise.
For example, if you have a function that just returns the length of a string or checks if a number is even, a single expression function is perfect. But if your function needs multiple steps or complex logic, use the regular function style with curly braces.
Key Points
- Single expression functions use
=and omit{}andreturn. - They make simple functions shorter and clearer.
- Best for functions with one clear expression.
- Not suitable for complex functions with multiple statements.