Start learning free

LESSON 49 OF 414 · FUNCTIONS I

Return in Scala: Fixing the Buggy Code

Practice Read the full explanation

We've written a program and expected it to print:

Hey bro!
How are you doing?

but we get a different output. Fix our code so that it prints what we want.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Buggy Code 6 in Scala, explained

    What the code is supposed to do

    The program should print two lines, in this order:

    Hey bro!
    How are you doing?
    

    The first line is meant to be printed from inside greetAndReturn. The second is the string that greetAndReturn returns, which mainFunction stores in question and prints.

    Here is the starting code:

    def greetAndReturn(): String = {
        return "How are you doing?"
        println("Hey bro!")
    }
    
    def mainFunction(): Unit = {
        val question = greetAndReturn()
        println(question)
    }
    

    It doesn't compile. The compiler reports a type mismatch: Found: Unit, Required: String.

    What goes wrong

    Two rules explain the error and the missing output.

    1. A block's value is its last expression. The body of greetAndReturn ends with println("Hey bro!"). A call to println has type Unit, but the function promises a String. That is the mismatch the compiler reports. The return on the line above doesn't change what the compiler thinks of the last line.
    2. return leaves the function immediately. Even if the code compiled, the println sits below the return, so the function would already be finished when it would run. "Hey bro!" could never be printed.

    The line is correct. Its position is the bug.

    Fixing it step by step

    1. Move the println above the return. Statements run top to bottom, so printing first guarantees the greeting appears before the function exits.
    2. End the function with the return. The last line of the body is now the string, of type String, which matches the declared result type. The type error disappears.
    3. Leave mainFunction alone. It already stores the returned string and prints it. That line comes second in the output, after the greeting printed inside greetAndReturn.

    The fixed code in Scala

    def greetAndReturn(): String = {
        println("Hey bro!")
        return "How are you doing?"
    }
    
    def mainFunction(): Unit = {
        val question = greetAndReturn()
        println(question)
    }
    

    When mainFunction() runs, the call to greetAndReturn() prints Hey bro! first, then returns the question. The println(question) line then prints How are you doing?.

    Scala details worth knowing:

    • return is optional. The last expression of a block is its value, so the function could end with just "How are you doing?". Both forms behave the same here.
    • Order of effects. The greeting prints while greetAndReturn is running, before val question receives its value. The returned string is printed later, by mainFunction.
    • Explicit result types. Because : String is written on the function, the compiler can compare the body against it. That is how the mistake was caught.

    Tracing the output

    Following the fixed program line by line shows why the order is right:

    1. mainFunction starts and evaluates the right side of val question = greetAndReturn(), which calls greetAndReturn.
    2. Inside, println("Hey bro!") runs, so the first output line appears.
    3. The return sends "How are you doing?" back, and question is bound to it. Nothing has been printed for it yet.
    4. println(question) prints the second line.

    If the two statements in greetAndReturn were swapped back, the order of the output would not be the only problem: the program would not even compile.

    Common mistakes

    • Deleting the println line. The compile error goes away, but the output loses Hey bro!.
    • Changing the return type to Unit. That compiles, with a warning about the discarded string, but question then holds (), the only value of Unit, and the program prints () instead of How are you doing?.
    • Printing the greeting in mainFunction instead. The lesson wants it inside greetAndReturn, and both lines must come out in the right order.
    • Putting any code after the return. It never runs, and the last expression of the block must stay the returned value.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free