Part 05 / Topic 2 of 8
Single-expression functions
When a function's entire body is one expression, the braces and return can go, and the body
sits directly after =.
fun square(x: Int): Int = x * x
fun isPrime(n: Int): Boolean {
if (n < 2) return false
for (i in 2 until n) {
if (n % i == 0) return false
}
return true
}
fun max(a: Int, b: Int) = if (a > b) a else b // return type inferred as Int
fun main() {
println("Square of 6: ${square(6)}")
println("Is 17 prime? ${isPrime(17)}")
println("Is 18 prime? ${isPrime(18)}")
println("Max of 8, 15: ${max(8, 15)}")
}
Square of 6: 36
Is 17 prime? true
Is 18 prime? false
Max of 8, 15: 15
square keeps its return type (Int) even as a single expression -- writing it is always
allowed and often clearer. max drops it: the compiler infers Int from the type of the
if/else expression itself. isPrime cannot be a single expression at all -- it needs several
return statements at different points, which only a block body with braces supports.
🔍 Going deeper: a single-expression function may omit its return type; a block-body function whose body does anything other than return
Unitmay not. Reaching intoisPrimeand stripping its: Booleanproduces a real, verified error, repeated for everyreturninside the block, because the compiler assumesUnitthe moment the return type is missing:error: return type mismatch: expected 'Unit', actual 'Boolean'. if (n < 2) return false ^^^^^The message is the giveaway: it isn't "you forgot a return type," it's "you told me (by omission) this returns
Unit, and then returned aBooleananyway."
Full program: examples/02_single_expression_functions.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.