Start learning free

LESSON 36 OF 414 · FUNCTIONS I

Function Parameters and Arguments in Scala

Lesson Read the full explanation

So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.

For example, it would be nice if sayHello() would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.


Function parameters:

Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

When a function is defined, its parameters are specified between the parentheses that follow the function name.

Here is our function with one String parameter, audience:

def sayHello(audience: String): Unit = {
  println("Hello " + audience)
}

Calling with arguments:

Then we can call sayHello() and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.

// Function declaration:
def sayHello(audience: String): Unit = {
	println("Hello " + audience)
}

// Function call:
sayHello("humans") // Output: Hello humans

We have passed one string argument: "humans". Inside the function audience will equal string "humans" and acts just like a regular variable.


Multiple parameters:

A function can have as many parameters as it needs. Here is a function with two parameters:

def sayHello(name: String, age: Int): Unit = {
  println(name + ", aged " + age)
}

// Let's call it:
sayHello("John", 30) // Output: John, aged 30
sayHello("Mary", 26) // Output: Mary, aged 26

Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.


Variables as arguments:

Variables can also be passed as arguments for function calls:

def sayHello(name: String, age: Int): Unit = {
  println(name + ", aged " + age)
}

var name = "Andy"
var age = 28

sayHello(name, age) // Output: Andy, aged 28

sayHello("Mary", age) // Output: Mary, aged 28

Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Function Parameters And Arguments in Scala, explained

    What parameters and arguments are

    A function that always does the same thing is of limited use. Parameters let a function receive input, so the same code can produce different results on each call. A parameter is a placeholder: a name, written in the parentheses of the definition, for a value that does not exist yet. An argument is the actual value you pass when you call the function. Inside the function, the parameter behaves like a normal variable holding that argument.

    The two words describe the two sides of one hand-off. The definition has parameters; the call has arguments.

    Defining a function with a parameter

    In Scala every parameter needs a name and a type, separated by a colon. The type is required: the compiler does not guess parameter types.

    def sayHello(audience: String): Unit = {
      println("Hello " + audience)
    }
    
    sayHello("humans")   // Hello humans
    sayHello("cats")     // Hello cats
    

    Here audience is the parameter and "humans" is the argument of the first call. Unit is the return type of a function that does its work (printing, here) and hands back nothing useful.

    Several parameters

    Separate parameters with commas. Arguments are matched to parameters by position: the first argument goes to the first parameter, the second to the second.

    def sayHello(name: String, age: Int): Unit = {
      println(name + ", aged " + age)
    }
    
    sayHello("John", 30)   // John, aged 30
    sayHello("Mary", 26)   // Mary, aged 26
    

    Scala also lets you name the arguments in a call, which makes the order irrelevant: sayHello(age = 26, name = "Mary") prints Mary, aged 26 too.

    Variables as arguments

    An argument can be any expression, including a variable. The function receives the value the variable holds at the moment of the call.

    val name = "Andy"
    val age = 28
    
    sayHello(name, age)      // Andy, aged 28
    sayHello("Mary", age)    // Mary, aged 28
    

    The variable name in the caller and the parameter name inside the function are two separate things that happen to share a name. Only the value travels between them.

    Building text with string interpolation

    Joining pieces with + works, but Scala has a tidier tool. A string literal with an s in front of the opening quote is an interpolated string: $name is replaced by the value of name, and ${expression} is replaced by the value of any expression.

    def show(n: Int): Unit = println(s"n+1 = ${n + 1}, n = $n")
    
    show(4)   // n+1 = 5, n = 4
    

    Without the s, nothing is replaced: println("Hello $name") prints the characters Hello $name.

    The exercise, step by step

    The lesson asks for a function welcomeUser and two calls to it.

    1. Define the function inside Solution, above mainFunction, with one String parameter called name and the return type Unit.
    2. Print the greeting with an interpolated string, so the text changes with the parameter: for "Andy" it must read Welcome, Andy!.
    3. Call it with a literal from mainFunction: welcomeUser("Andy").
    4. Create a variable in mainFunction. A val is the right choice because the value never changes.
    5. Call it with the variable as the argument, to show that an argument doesn't have to be a literal.
    class Solution {
        def welcomeUser(name: String): Unit = {
            println(s"Welcome, $name!")
        }
    
        def mainFunction(): Unit = {
            welcomeUser("Andy")
            val name = "John"
            welcomeUser(name)
        }
    }
    

    Running mainFunction prints:

    Welcome, Andy!
    Welcome, John!
    

    Common mistakes

    • Too few or too many arguments. Calling sayHello("John") when two parameters are required fails to compile with missing argument for parameter age of method sayHello.
    • Wrong order or types. sayHello(30, "John") does not compile: the compiler reports Found: Int, Required: String for the first argument and the reverse for the second.
    • Assigning to a parameter. Parameters are read-only. Writing n = n + 1 inside a function whose parameter is n fails with Reassignment to val n. Compute a new value instead.
    • Forgetting the s prefix. The text then contains a literal $name.
    • A parameter that is never used. The code compiles, but every call behaves the same. A parameter only matters if the body reads it.

    Key takeaways

    • Parameters are declared in the definition, with a name and a type each; arguments are the values passed in the call.
    • Arguments are matched to parameters by position, or by name when you write name = value.
    • Any expression can be an argument, including a variable or a computed value.
    • Use s"... $name ..." to put a parameter inside a string.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free