Declaring functions
A function starts with fun, then its name, its parameters in parentheses (each written name: Type) and its return type after a colon. Parameters are read-only — you cannot reassign them inside the function. When the whole body is one expression, drop the braces and return and write = expression: a single-expression function. The compiler can infer the return type of a single-expression function; a block body with a result always needs it written.
// Block body: braces, explicit return type, return statement
fun bmi(weightKg: Double, heightM: Double): Double {
val value = weightKg / (heightM * heightM)
return value
}
// Single-expression function: return type inferred as Boolean
fun isAdult(age: Int) = age >= 18
fun category(bmi: Double): String = when {
bmi < 18.5 -> "under"
bmi < 25.0 -> "normal"
else -> "over"
}
fun main() {
val b = bmi(70.0, 1.75)
println("%.1f".format(b))
println(category(b))
println(isAdult(17))
}22.9
normal
falseFunctions declared at the top of a file, outside any class, are top-level functions. Kotlin does not need a class to hold them, unlike Java.
Write fun circleArea(r: Double) = … as a single-expression function using Math.PI, and print the area for radius 2.
A block body with no return
fun square(x: Int): Int {
x * x
}
fun main() {
println(square(4))
}Main.kt:3:1: error: missing return statement.In a block body the last expression is not returned automatically — that rule is for lambdas and if/when branches. The function promised an Int and reaches its closing brace without handing one back.
Add return, or turn it into a single-expression function.
fun square(x: Int): Int = x * x
fun main() {
println(square(4))
}