Single-Expression Functions
In this page:
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
fun square(x: Int) = x * x
fun main() {
println("Square of 6: ${square(6)}")
}
Login to try C/C++/Java/PHP code in the editor
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
fun greeting(name: String) = "Hello, $name!"
fun main() {
println(greeting("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
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
fun classify(n: Int) = if (n % 2 == 0) "even" else "odd"
fun main() {
println("7 is ${classify(7)}")
println("8 is ${classify(8)}")
}
Login to try C/C++/Java/PHP code in the editor
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
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))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
=sign; single-expression functions use= expressioninstead of a block body. - Trying to write multiple statements in a single-expression function; it must be exactly one expression.
- Adding an unnecessary explicit return type when it can be safely inferred from the expression.
- 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: