← Back to Kotlin Course | Chapter 4: Functions | Lesson 4 of 7

Single-Expression Functions

A single-expression function skips the curly braces entirely when the whole job can be written as one short formula.

Writing a Single-Expression Function

Instead of { return ... }, a function body can be a single = expression, which is both shorter and often clearer for simple computations.

Example: Writing a Single-Expression Function

markup
fun square(x: Int) = x * x

fun main() {
    println("Square of 6: ${square(6)}")
}

Return Type Inference

Kotlin infers the return type of a single-expression function from the expression itself, so it is usually unnecessary to write it explicitly.

Note: An explicit return type is still required for public API functions in larger projects, for documentation clarity.

Example: Return Type Inference

markup
fun greeting(name: String) = "Hello, $name!"

fun main() {
    println(greeting("Kotlin"))
}

Using if/when Expressions

Because if and when are expressions in Kotlin, a single-expression function body can contain fairly rich logic while remaining just one expression.

Example: Using if/when Expressions

markup
fun classify(n: Int) = if (n % 2 == 0) "even" else "odd"

fun main() {
    println("7 is ${classify(7)}")
    println("8 is ${classify(8)}")
}

When Not to Use This Style

Single-expression syntax is best kept for short, genuinely single-expression logic; anything requiring multiple statements or intermediate variables should use a normal block body instead.

Example: When Not to Use This Style

markup
fun describeNumber(n: Int): String {
    val parity = if (n % 2 == 0) "even" else "odd"
    val sign = if (n >= 0) "non-negative" else "negative"
    return "$n is $parity and $sign"
}

fun main() {
    println(describeNumber(-4))
}
Common Mistakes
  1. Forgetting the = sign; single-expression functions use = expression instead of a block body.
  2. Trying to write multiple statements in a single-expression function; it must be exactly one expression.
  3. Adding an unnecessary explicit return type when it can be safely inferred from the expression.
Chapter Summary
  • A single-expression function is written as fun name(params) = expression, without curly braces.
  • The return type can usually be inferred from the expression, so it is often omitted.
  • This style suits short, simple computations, not multi-statement logic.
  • A single-expression function still supports parameters and default values just like a block-bodied one.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.