Start learning free

LESSON 35 OF 414 · FUNCTIONS I

Create a Function in Scala: Removing Repeated println Calls

Practice Read the full explanation

We've written this code:

def mainFunction(): Unit = {
	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 5
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Exercise Create Function in Scala, explained

    Problem overview

    The starting code prints three messages, and then prints the same three messages two more times. It has nine println statements in one function:

    def mainFunction(): Unit = {
        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!")
    }
    

    The task is to produce the same output in a better way: create a function named printMessages that prints the three messages, and call it three times.

    Approach: extract the repeated block

    The nine lines are one block of three lines, copied three times. When code repeats like this, move the block into a function, then replace every copy with a call. The output stays the same, but the three messages are written only once.

    That gives the program two parts:

    • a function printMessages that holds the three println statements;
    • mainFunction, which calls printMessages once per repetition.

    Step by step

    1. Define printMessages above mainFunction. Use def, the name, empty parentheses and the result type Unit, because the function prints and returns nothing useful. Finish the line with = {.
    2. Put one copy of the three messages in the body. They go inside the braces, in the same order as before, with the exact text, including the capital letters and exclamation marks.
    3. Close the braces. The function is now defined, but defining it prints nothing.
    4. Call it three times in mainFunction. Each printMessages() runs the three println statements once. Three calls produce the original nine lines, with no println left in mainFunction.

    The solution in Scala

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

    Running mainFunction() prints:

    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!
    

    The Scala details worth knowing:

    • Parentheses on the call. In Scala 3, a method defined with () must be called with (). Writing printMessages alone is rejected with method printMessages must be called with () argument.
    • Unit. It marks a function that returns no useful value. The last expression of the body is a println, whose value is (), which matches.
    • Order of definitions. The function is defined above mainFunction, which is the clear order for readers.
    • The comments. Lines starting with // are ignored by the compiler. They are only there to mark where each part goes.

    Why this is better

    Compare the two versions when the requirements change:

    • If the messages must be printed five times, the new version needs two more calls. The original needs six more lines.
    • If one message needs different wording, the new version has one place to edit. The original has three copies of it.

    The three identical calls are still repetition. A loop would remove it, and later lessons cover loops. The function you write here stays useful either way.

    Edge cases and common mistakes

    • Defining the function but calling it fewer than three times. The output would have too few lines. Count the calls.
    • Keeping the original println lines in mainFunction. They would print in addition to the calls, so the output would have too many lines.
    • Misspelling the name. The task names printMessages, with a capital M. Scala names are case-sensitive.
    • Changing the text. The tests compare the exact output, so every character of the messages counts.
    • Leaving out the parentheses in the calls. That doesn't compile.

    Testing

    Run mainFunction() and check that the output has 9 lines, made of the three messages repeated three times in order. If you call printMessages() once, you should see exactly the first three lines.

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