Start learning free

LESSON 40 OF 414 · FUNCTIONS I

Create a Function with Parameters in Scala

Practice Read the full explanation

We've written this code:

def mainFunction(): Unit = {
	println("My name is Andy")
	println("I code in Python")
	println("I have a dog")

	println("My name is Mike")
	println("I code in Java")
	println("I have a cat")

	println("My name is Sarah")
	println("I code in JavaScript")
	println("I have a parrot")
}

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

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Exercise Create Function With Parameters in Scala, explained

    Problem overview

    The starting code prints three introductions, nine println calls in all. Each introduction has the same three sentences, and only the name, the language and the pet change:

    My name is Andy
    I code in Python
    I have a dog
    

    The task is to write the same program better: one function, printMessages, that takes the changing parts as parameters, and three calls to it.

    Approach

    Look at which words change between the three blocks: the name (Andy, Mike, Sarah), the language, and the animal. Those three values become the parameters. Everything else, the words "My name is", "I code in" and "I have a", stays inside the function body, written once.

    This is the same move as in any refactoring: find the repeated shape, name the parts that vary, and let the caller supply them. The repeated version has nine lines to read and to keep consistent. The new version has three lines of logic and three short calls, and adding a fourth person costs one more call instead of three more println lines.

    Step by step

    1. Define the function above mainFunction with three String parameters, name, language and animal, and the return type Unit, because it prints and returns nothing.
    2. Print each sentence with an interpolated string. The s in front of the quote makes $name expand to the parameter's value.
    3. Call the function three times from mainFunction, passing the values in the same order as the parameters: name, language, animal.

    The solution in Scala

    // Define & implement the function printMessages here:
    def printMessages(name: String, language: String, animal: String): Unit = {
        println(s"My name is $name")
        println(s"I code in $language")
        println(s"I have a $animal")
    }
    
    
    def mainFunction(): Unit = {
        // Call printMessages 3 times here:
        printMessages("Andy", "Python", "dog")
        printMessages("Mike", "Java", "cat")
        printMessages("Sarah", "JavaScript", "parrot")
    }
    

    Running mainFunction prints:

    My name is Andy
    I code in Python
    I have a dog
    My name is Mike
    I code in Java
    I have a cat
    My name is Sarah
    I code in JavaScript
    I have a parrot
    

    A few Scala details:

    • The s prefix is required. Without it, "My name is $name" is an ordinary string and prints the characters $name literally.
    • Each parameter has a type. Scala does not infer parameter types, so name: String cannot be shortened to name.
    • The text before the dollar sign is kept as written. In s"I have a $animal" the space after a is part of the output, so the result reads I have a dog.

    Return type

    The function ends with : Unit = because its job is a side effect, printing. It computes no result for the caller to use. If you wanted the three sentences back as a value instead, you would give the function a String return type and let the caller decide what to do with the text. This lesson only needs the printing version.

    Testing

    Try a fourth call, such as printMessages("Zoe", "Scala", "fish"). It prints My name is Zoe, I code in Scala and I have a fish without any change to the function. That is the sign the parameters are doing their job.

    Common mistakes

    • Passing arguments in the wrong order. Swapping the language and the animal compiles, since both are strings, and prints sentences like I code in dog.
    • Passing too few arguments. printMessages("Andy", "Python") fails with missing argument for parameter animal of method printMessages.
    • Forgetting to call the function. Defining printMessages prints nothing by itself. Output appears only when mainFunction calls it.
    • Copying the first block into the function. If the body still says "My name is Andy", all three calls print the same text. Every changing value has to come from a parameter.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free