Start learning free

LESSON 45 OF 677 · FUNCTIONS I

Fixing println Instead of a Return Value in Scala

Practice Read the full explanation

We've written a program and expected it to print Hey, Andy but when we run it we get some errors.

Fix our code so that it works and prints what we want.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Buggy Code Print Instead Of Return in Scala, explained

    What the code is supposed to do

    The method getGreeting should build a greeting for a name and give it back. mainFunction calls it with "Andy", stores the result and prints it, so the program should print Hey, Andy exactly once.

    The code you start with does not compile:

    class Solution {
        def getGreeting(name: String): String = {
            println("Hey, " + name)
        }
    
    
        // Do not change the code below:
        def mainFunction(): Unit = {
            val greeting = getGreeting("Andy")
            println(greeting)
        }
    }
    

    What goes wrong

    The compiler reports a type mismatch:

    -- [E007] Type Mismatch Error ---
    3 |        println("Hey, " + name)
      |        ^^^^^^^^^^^^^^^^^^^^^^^
      |        Found:    Unit
      |        Required: String
    

    The header says getGreeting returns a String. The body, however, only calls println, which writes the text to the console and returns Unit. Because the value of a block is its last expression, the method's result is that Unit. The greeting was built and shown, but it was never handed back, so the caller has nothing to store in greeting.

    The mistake is mixing up two jobs. Printing is for people reading the console. Returning is for the code that called the function. Here the calling code already does the printing, so the method should only produce the text.

    Fixing it step by step

    1. Read the types. Found: Unit and Required: String say that the body ends with something that isn't text.
    2. Notice who prints. mainFunction already has println(greeting). If the method printed as well, the greeting would appear twice.
    3. Replace the print with a return. Remove the println call and give back the string it was building, "Hey, " + name.
    4. Leave the code below the comment alone. It is correct once the method returns a value.

    The fixed code in Scala

    class Solution {
        def getGreeting(name: String): String = {
            return "Hey, " + name
        }
    
    
        // Do not change the code below:
        def mainFunction(): Unit = {
            val greeting = getGreeting("Andy")
            println(greeting)
        }
    }
    

    Now getGreeting("Andy") returns the text Hey, Andy, greeting holds it, and the single println in mainFunction prints it.

    Scala doesn't need the return keyword here. Making the string the last expression does the same job:

    def getGreeting(name: String): String = {
        "Hey, " + name
    }
    

    Both forms work. The one thing to avoid is ending the body with a call whose type is Unit, when the header promises something else.

    Why returning is the better design

    A method that returns its text can be used in many ways: printed, stored, compared, or joined with other text. A method that prints decides for every caller that the text goes to the console, and nobody else can use it. Keeping the building of values in methods and the printing in the caller is a pattern you will use throughout the course.

    Common mistakes

    • Keeping both a print and a return. If the body prints and then returns, the greeting appears twice: once from the method and once from mainFunction.
    • Changing the return type to Unit. The method would compile, but greeting would then hold (), so the first println would print Hey, Andy and the second would print ().
    • Removing the print from mainFunction. That part was already correct, and the task says not to change it. Without a print there, nothing would be shown.
    • Misspelling the text. The output has to match exactly, including the comma and the space after it.

    Checking your fix

    Run the code in the editor above. A correct fix compiles and prints one line, Hey, Andy.

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