Single-Expression Functions
The = shorthand for functions whose body is one expression, and how it works with type inference.
読了時間 2 分
When a function's entire body is a single expression, Kotlin lets you skip the curly braces and return keyword entirely, using = instead:
fun square(x: Int): Int {
return x * x
}
// Equivalent, as a single-expression function
fun square(x: Int): Int = x * xBoth versions compile to the same thing and behave identically. The second is simply a more direct way of saying "this function's result is exactly this expression."
Return type inference
Once a function is written this way, Kotlin can usually infer the return type from the expression itself, letting you drop it too:
fun square(x: Int) = x * x
fun greet(name: String) = "Hello, $name!"
fun isEven(n: Int) = n % 2 == 0The compiler looks at x * x and sees it's an Int, so square's return type is Int — you never had to write it. This is the same type inference from earlier in the course, just applied to a function's return type instead of a variable.
Combining with if and when
Because if and when are expressions in Kotlin, they slot directly into a single-expression function body:
fun max(a: Int, b: Int) = if (a > b) a else b
fun describe(n: Int) = when {
n < 0 -> "negative"
n == 0 -> "zero"
else -> "positive"
}
println(max(3, 7)) // 7
println(describe(-5)) // negativeNeither of these functions needed a return statement at all — the whole body is one expression that evaluates to the answer.
When to write the full form instead
Single-expression syntax is a convenience for simple logic, not a requirement everywhere. Once a function needs multiple statements — a loop, several local variables, or logic that doesn't reduce to one expression — the block form with explicit return is clearer and should be preferred:
fun calculateAverage(numbers: List<Int>): Double {
if (numbers.isEmpty()) return 0.0
val total = numbers.sum()
return total.toDouble() / numbers.size
}Trying to force this into a single expression would hurt readability rather than help it — the block form here says exactly what's happening, one step at a time.
Why explicit return types on public functions still make sense
Even though Kotlin can infer a single-expression function's return type, it's common practice to write it explicitly on public API functions:
fun calculateDiscount(price: Double): Double = price * 0.9This protects against a subtle problem: if you later change the expression in a way that changes its inferred type, an explicit return type turns that into an immediate, visible compile error at the function itself, rather than a confusing type mismatch somewhere else that called it.
The next lesson introduces lambdas — functions without a name, passed around as values — and the higher-order functions that take them as arguments.