What a function is
A function is a named container for a few lines of code that perform one task. Instead of writing one long list of instructions, you break the program into small pieces, give each piece a name and run it by that name. The code is easier to read, and a task you need several times is written only once.
In Kotlin, a function is defined with the keyword fun:
fun functionName(): returnType {
// function body
}
A function has two parts.
- The header holds the keyword
fun, the function's name, a pair of parentheses and, optionally, the return type after a colon. The parentheses can hold parameters, which a later lesson covers. For now they stay empty. - The body is the code that runs when the function is called, placed between curly braces.
A function that doesn't return anything useful has the return type Unit. You don't have to write it: when a function with a block body has no return type, Kotlin uses Unit for it. So these two headers mean the same thing:
fun sayHello() {
println("Hello World")
}
fun sayHelloAgain(): Unit {
println("Hello World")
}
The body is indented by four spaces. Kotlin doesn't need that, because the braces mark where the body begins and ends, but indentation lets a reader see at a glance which lines belong to the function.
Defining is not running
A definition only tells Kotlin that the function exists. If you run a program that contains just sayHello as above, nothing is printed. The body runs only when the function is called, which means writing its name followed by parentheses:
fun sayHello() {
println("Hello World")
}
fun main() {
sayHello()
sayHello()
}
Hello World
Hello World
Each call runs the whole body from top to bottom, so two calls print the message twice. A function can be called as many times as you need.
Kotlin details worth knowing
- The parentheses make it a call. Writing only
sayHellorefers to the function without running it, and the compiler rejects it as a statement with the errorfunction invocation 'sayHello()' expected. - Calls belong inside functions. A Kotlin file may contain declarations such as functions at its top level, but a bare call like
sayHello()there is a syntax error. Calls go inside the body of another function, such asmainin a standalone program ormainFunctionin this lesson. - Order of definitions doesn't matter. A function can call another one that is written further down the file, because Kotlin knows about all the declarations of a file before it runs anything.
- The call evaluates to
Unit. Printing the result of a call tosayHello()would showkotlin.Unit, sinceUnitis a real value, but you rarely need it.
The lesson's exercise, step by step
The starter code is an empty mainFunction, with comments marking where the new code goes.
- Define
sayHelloabovemainFunction. Usefun, the name, empty parentheses and a pair of braces. - Print the greeting inside the braces. A
println("Hello everybody!")call in the body makes the function do something, and it runs every time the function is called. - Call
sayHello()frommainFunction. Without the call, the definition would never execute and nothing would be printed.
The finished code is:
fun sayHello() {
println("Hello everybody!")
}
fun mainFunction() {
sayHello()
}
Common mistakes
- Defining the function but never calling it. The program compiles and prints nothing.
- Leaving out the parentheses in the call.
sayHelloalone doesn't compile. - Putting the
printlnoutside the braces. A statement outside any function doesn't belong to the function, and in a Kotlin file it is a syntax error. - Misspelling the name. Names are case-sensitive, so
sayhello()is notsayHello(). The compiler reports an unresolved reference.
Key takeaways
- A function is defined with
fun, a name, parentheses and a body in curly braces. - Without a written return type, a block-body function returns
Unit. - Defining a function doesn't run it. Calling it, with the name and parentheses, does, and every call runs the whole body.