Part 05 / Topic 1 of 8
Declaring a function
A function has a name, a parameter list (each parameter needs an explicit type -- Kotlin never
infers a parameter's type from how it is called), and a return type written after :.
fun add(a: Int, b: Int): Int {
return a + b
}
fun gstAmount(amount: Double): Double {
return amount * 0.18
}
fun farewell(name: String) {
println("Goodbye, $name")
}
fun main() {
println("3 + 4 = ${add(3, 4)}")
println("GST on ₹1000.0: ₹${gstAmount(1000.0)}")
farewell("Meera")
}
3 + 4 = 7
GST on ₹1000.0: ₹180.0
Goodbye, Meera
add, gstAmount and farewell are top-level functions: declared directly in the file, not
inside any class, sitting right alongside main() itself. farewell has no : and no return
type at all -- it only prints, so there is nothing meaningful to hand back (section 3 names this
properly).
🔍 Going deeper: Part 1 showed that a top-level
fun main()compiles into a class named after the file (FileNameKt). Every other top-level function in that same file compiles into the same class, as astaticmethod sitting next tomain:$ kotlinc 01_declaring_functions.kt -d out01 $ javap -p out01/_01_declaring_functionsKt.class Compiled from "01_declaring_functions.kt" public final class _01_declaring_functionsKt { public static final void main(); public static final int add(int, int); public static final double gstAmount(double); public static final void farewell(java.lang.String); public static void main(java.lang.String[]); }
add,gstAmountandfarewellshow up asstaticmethods on_01_declaring_functionsKt, the exact same classmainlives in -- "top-level" doesn't mean "nowhere," it means "the JVM puts it on the file's own generated class," which is why a top-level function never needs an object to call it on.
Full program: examples/01_declaring_functions.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.