Start learning free

LESSON 28 OF 414 · FUNCTIONS I

Functions in Scala: Defining and Calling with def

Lesson Read the full explanation

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in Scala:

def functionName(): ReturnType = {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • def is the keyword that starts a function definition
  • ReturnType which is the type of the value returned by the function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that Scala executes whenever the function is called.

It consists of one or more Scala statements placed inside curly brackets {} (where we have our Scala comment).

Here's an example of a function:

def sayHello(): Unit = {
	println("Hello World")
}

The return type of this function is Unit, which means the function is not returning a useful value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our println("Hello World").

Indentation is not required when we use curly braces, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
def sayHello(): Unit = {
	println("Hello World")
}
	
// Function call:
sayHello() // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the console.

We can call a function as many times as it is needed.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · FUNCTIONS I

    Functions in Scala, explained

    What a function is

    A function is a named container for a few lines of code that perform one task. Splitting a program into functions keeps each piece small and gives every piece a name that says what it does. Once a function exists, you can run it as many times as you like without copying its code.

    Strictly speaking, a def inside a class or object is called a method in Scala. The lessons call them functions, and for the simple cases here the difference doesn't matter.

    The shape of a definition

    def functionName(): ReturnType = {
        // function body
    }
    

    A definition has two parts.

    The header

    • def is the keyword that starts a function definition.
    • functionName is the name you use to call it. Scala names are case-sensitive, and the usual style is camelCase.
    • The parentheses hold the parameters. They are empty here because the function takes no input; later lessons fill them in.
    • ReturnType, written after a colon, is the type of the value the function gives back.
    • The = sign connects the header to the body. It is required: without it, Scala sees only a declaration with no body.

    The body

    The body is the code that runs when the function is called, wrapped in curly braces. Indent it so readers can see where it belongs. Scala doesn't require the indentation, but it makes the code far easier to read.

    The Unit return type

    def sayHello(): Unit = {
        println("Hello World")
    }
    

    This function prints a message and gives nothing useful back, so its return type is Unit. Unit is Scala's "no meaningful value" type, similar to void in other languages. It has exactly one value, written (). If you store the result of calling such a function, you get that value:

    val r = sayHello()
    println(r)
    

    This prints Hello World and then ().

    Defining is not running

    A definition only tells Scala that the function exists. Its body doesn't run until something calls it. If you define sayHello and do nothing else, nothing is printed.

    To call a function, write its name followed by parentheses:

    def sayHello(): Unit = {
        println("Hello World")
    }
    
    sayHello()
    

    This prints Hello World. The parentheses are part of the call. A method defined with () must be called with () in Scala 3: writing just sayHello is rejected with method sayHello must be called with () argument.

    Every call runs the whole body from the top. Calling sayHello() twice prints the message twice.

    The lesson's exercise

    The starter code has an empty function named mainFunction, and you add a function above it.

    1. Define sayHello above mainFunction. Use def, empty parentheses, the result type Unit and = {, since the function prints instead of returning a value.
    2. Print the message inside the braces. println("Hello everybody!") goes in the body, because the body is what runs on each call.
    3. Call it from mainFunction. Writing sayHello() there is what makes the message appear.

    The solution:

    def sayHello(): Unit = {
        println("Hello everybody!")
    }
    
    def mainFunction(): Unit = {
        sayHello()
    }
    

    Running mainFunction() prints Hello everybody! once. Note that mainFunction is a function like any other: its body calls sayHello(), and a third function could call mainFunction() in the same way.

    Common mistakes

    • Forgetting the =. def sayHello(): Unit alone declares a method without a body.
    • Defining but never calling. The program then prints nothing.
    • Leaving out the parentheses in the call. Use sayHello(), not sayHello.
    • Misspelling the name or changing its case. sayhello() isn't the same as sayHello().
    • Putting the println outside the braces. It then belongs to the surrounding code, not to the function.

    Key takeaways

    • A function is defined with def, a name, parentheses, a return type, = and a body in braces.
    • Unit means the function returns no useful value.
    • The body runs only when the function is called, and it runs in full on every call.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free