Start learning free

LESSON 28 OF 348 · FUNCTIONS I

Functions in Kotlin: Defining and Calling with fun

Lesson Read the full explanation

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in Kotlin:

fun functionName(): returnType {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • returnType which is the type of the value returned by the function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that Kotlin executes whenever the function is called.

It consists of one or more Kotlin statements placed inside curly brackets {} (where we have our Kotlin comment).

Here's an example of a function:

fun sayHello() {
	println("Hello World")
}

The return type of this function is Unit, which means the function is not returning any value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our println("Hello World").

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
fun sayHello() {
	println("Hello World")
}

// Function call:
sayHello() // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS I

    Functions in Kotlin, explained

    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 sayHello refers to the function without running it, and the compiler rejects it as a statement with the error function 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 as main in a standalone program or mainFunction in 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 to sayHello() would show kotlin.Unit, since Unit is 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.

    1. Define sayHello above mainFunction. Use fun, the name, empty parentheses and a pair of braces.
    2. 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.
    3. Call sayHello() from mainFunction. 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. sayHello alone doesn't compile.
    • Putting the println outside 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 not sayHello(). 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.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free