Start learning free

LESSON 35 OF 348 · FUNCTIONS I

Create a Function in Kotlin: Removing Repeated println Calls

Practice Read the full explanation

We've wrritten this code:

fun mainFunction() {
	println("Hello AlgoCademy!")
	println("Coding is amazing!")
	println("Functions are so useful!")

	println("Hello AlgoCademy!")
	println("Coding is amazing!")
	println("Functions are so useful!")

	println("Hello AlgoCademy!")
	println("Coding is amazing!")
	println("Functions are so useful!")
}

Write the same code in a better way by creating and calling a function printMessages()

STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · FUNCTIONS I

    Exercise Create Function in Kotlin, explained

    Problem overview

    The exercise starts with a mainFunction that prints three messages and then prints the same three messages two more times, nine println calls in all:

    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    

    The three lines appear three times in a row. Your task is to produce the same output with less code, by creating a function named printMessages and calling it where the repeated lines were.

    Approach: move the repeated block into a function

    When the same group of statements appears several times, put the group in a function once and replace each copy with a call. The output doesn't change, but the code gets shorter, and a change to a message needs to be made in only one place.

    The group here is the three println lines. The function needs no input, because the messages are always the same, and it needs no result, because it only prints. That makes it the simplest kind: no parameters, and the default return type Unit.

    Step by step

    1. Define printMessages above mainFunction. Use fun, the name, empty parentheses and braces.
    2. Move one copy of the three println calls into the body, in their original order and with the messages spelled exactly as before.
    3. Clear out the old repeated lines from mainFunction. They are replaced by calls, so none should stay.
    4. Call printMessages() three times in mainFunction, once for each repetition of the original.

    The solution in Kotlin

    // Define and implement the function printMessages here:
    fun printMessages() {
        println("Hello AlgoCademy!")
        println("Coding is amazing!")
        println("Functions are so useful!")
    }
    
    fun mainFunction() {
        // Call printMessages 3 times here:
        printMessages()
        printMessages()
        printMessages()
    }
    

    The Kotlin details worth noticing:

    • Parentheses on both sides. They follow the name in the definition, where they are empty because there are no parameters. They follow the name in every call, too. A bare printMessages is only a reference to the function, and as a statement the compiler rejects it with function invocation 'printMessages()' expected.
    • The return type is implied. With a block body and no declared type, the function returns Unit. Writing fun printMessages(): Unit is allowed and means the same.
    • Definition order. The function is written above mainFunction here, which is the clearest layout for a reader. Kotlin would also accept it below.
    • No semicolons. A line break ends each statement.

    Seeing the result

    Run through a main that calls mainFunction(), the solution prints the nine lines of the original, each group in the same order:

    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    Hello AlgoCademy!
    Coding is amazing!
    Functions are so useful!
    

    Edge cases and common mistakes

    • Defining the function and not calling it. The code compiles and prints nothing, because a definition alone never runs the body.
    • Calling it the wrong number of times. Two calls print six lines, and four print twelve. The original prints three groups, so the code needs three calls.
    • Leaving some println lines in mainFunction. The output would then contain extra lines, and the duplication the exercise removes would still be there.
    • Changing the text. A different capital letter or a missing exclamation mark changes the output. Copy each message exactly.
    • Changing the name. Names are case-sensitive, so PrintMessages or printMessage is not printMessages.

    Where this leads

    Three calls in a row are still a repetition, because the same call is written three times. A loop, introduced later in the course, repeats a call for you, so that a hundred repetitions need no more code than three.

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