Start learning free

LESSON 36 OF 348 · FUNCTIONS I

Function parameters & arguments in Scala in Scala

Lesson

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

    Function Parameters And Arguments in Scala

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