Start learning free

LESSON 29 OF 348 · FUNCTIONS I

Defining a Function in Kotlin: Fixing the Buggy Code

Practice Read the full explanation

Inside the code editor we've tried just to define a function (without calling the function) that would print the message Hey, Andy! whenever called.

It seems like we made some mistakes because when we run our code we get an error.


Assignment:

Your task is to fix our function definition such that no errors will be produced.

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS I

    Buggy Code Defining A Function in Kotlin, explained

    What the code is supposed to do

    The goal is small: define a function named sayMyName that prints Hey, Andy! every time it is called. The task asks only for the definition. Nothing calls the function, so a correct answer compiles and prints nothing when it runs.

    The code you start with looks almost right, but it doesn't compile:

    fun sayMyName()
    println("Hey, Andy!")
    

    Your job is to find out why and fix the definition so the compiler accepts it.

    What goes wrong

    A person reading those two lines guesses that the second line belongs to the first. The compiler doesn't guess. It reads fun sayMyName() as a function header with nothing after it, then treats println("Hey, Andy!") as a separate piece of code that has nothing to do with sayMyName.

    That single misunderstanding causes two problems:

    1. The function has no body. In Kotlin, a function's body is normally the block between curly braces that follows the header. A function declared on its own like this must have one, so the compiler reports that sayMyName is missing its body.
    2. The print line belongs to no function. In a regular Kotlin source file, only declarations such as functions, classes and properties can stand at the top level. A statement like a println call has to live inside a function body, where it runs when that function is called.

    Because the code doesn't compile, the program never starts, and you see an error instead of any output.

    Why the braces matter

    Every Kotlin function definition has the same parts:

    • the keyword fun, which starts a function declaration;
    • the function's name, here sayMyName;
    • a pair of parentheses holding the parameters, empty here because the function needs no input;
    • an optional return type after a colon, left out here;
    • the body: the statements to run, wrapped in { and }.

    The braces are the only thing that tells the compiler where the body starts and where it ends. Line breaks and indentation don't count. Kotlin ignores indentation entirely, so indenting println under the header would make the code look correct to a person while leaving both errors in place. Indentation is a habit for readers; braces are the rule for the compiler.

    Fixing it step by step

    1. Keep the header as it is. fun sayMyName() is a correct header: the keyword, the exact name the task asks for and empty parentheses.
    2. Open the body. Add { at the end of the header line. That is the usual Kotlin style, and it tells the compiler the body starts here.
    3. Move the statement inside. The println line now sits between the braces, indented by four spaces so readers can see it belongs to the function.
    4. Close the body. Put } on its own line below the statement, lined up with fun.
    5. Leave out the call. The task says to define the function, not to call it, so don't add sayMyName() anywhere.

    The fixed code in Kotlin

    fun sayMyName() {
        println("Hey, Andy!")
    }
    

    A few Kotlin details are worth knowing about these three lines:

    • The hidden return type. A function that doesn't return a useful value has the return type Unit. When you leave the type out of a block-body function, Kotlin uses Unit, so writing fun sayMyName(): Unit { means the same thing.
    • println adds a line break. It prints its argument and then moves to a new line. print would print the same text without the line break.
    • The exact text matters. The message is a string literal in double quotes, and its comma, space and exclamation mark are all part of the output. "Hey Andy!" would print something different.
    • No semicolons needed. Kotlin ends a statement at the end of the line, so println("Hey, Andy!") needs nothing after it.
    • A one-line alternative. When a body is a single expression, Kotlin also accepts an expression body: fun sayMyName() = println("Hey, Andy!"). It behaves the same way. The block form above is the one this lesson uses, and it's the form you'll need as soon as a function has more than one statement.

    Defining is not running

    Once the definition compiles, nothing has been printed yet. The body only runs when something calls the function by writing its name followed by parentheses. In a standalone Kotlin program, that call goes inside main, the function where the program starts:

    fun sayMyName() {
        println("Hey, Andy!")
    }
    
    fun main() {
        sayMyName() // Hey, Andy!
        sayMyName() // Hey, Andy! (each call runs the body again)
    }
    

    This example is only for seeing the function in action. For this lesson, submit the definition alone.

    Common mistakes

    • Indenting instead of adding braces. The code looks right but still has a function without a body and a statement outside any function.
    • Forgetting the closing brace. The compiler reaches the end of the code while still inside the body and reports a missing }.
    • Braces in the wrong place. fun sayMyName() {} followed by the println line gives the function an empty body and leaves the statement outside it, so the original problem remains.
    • Changing the name. Kotlin names are case-sensitive: saymyname or SayMyName declares a different function from the sayMyName the task asks for.
    • Adding a call. Calling the function prints the message, which the task didn't ask for.

    Checking your fix

    Make the change in the editor above and run it. A correct fix compiles without errors and prints nothing, because the function is defined but never called. To see the message itself, run the two-function program from the previous section as a Kotlin program of your own: it prints Hey, Andy! once per call.

    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free