0
0
Kotlinprogramming~5 mins

Single-expression functions in Kotlin

Choose your learning style9 modes available
Introduction

Single-expression functions let you write simple functions in one line. This makes your code shorter and easier to read.

When your function returns a simple calculation or value.
When you want to write clear and concise code.
When the function body has only one expression.
When you want to avoid writing curly braces and return statements.
When you want to quickly define small helper functions.
Syntax
Kotlin
fun functionName(parameters): ReturnType = expression

The equals sign = replaces the usual curly braces and return statement.

The expression after = is automatically returned.

Examples
This function returns the square of a number in one line.
Kotlin
fun square(x: Int): Int = x * x
Return type is inferred here because Kotlin can guess it from the expression.
Kotlin
fun greet(name: String) = "Hello, $name!"
This function returns true if the number is even, false otherwise.
Kotlin
fun isEven(num: Int) = num % 2 == 0
Sample Program

This program defines a single-expression function add that adds two numbers. It then prints the result.

Kotlin
fun add(a: Int, b: Int): Int = a + b

fun main() {
    val result = add(5, 7)
    println("5 + 7 = $result")
}
OutputSuccess
Important Notes

Single-expression functions are great for simple logic but avoid using them for complex code blocks.

If your function needs multiple statements, use the regular function body with curly braces.

Summary

Single-expression functions let you write short functions in one line.

They automatically return the value of the expression after the equals sign.

Use them to make your code cleaner and easier to read.