Start learning free

LESSON 41 OF 677 · FUNCTIONS I

Returning from functions in Scala

Lesson

In the previous lessons, we have used Unit in the function declaration. This means the function is not returning a useful value.

It's also possible to return a value from a function. For this, we need to specify the return type of the function during function declaration.

Inside the function, we can use the return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

def plusThree(num: Int): Int = {
	return num + 3
}

// Inside main function:
val answer = plusThree(5)
println(answer) // Output: 8

Here, we have the data type Int instead of Unit. This means that the function returns an Int value.

plusThree takes an Int argument for num and returns an Int value equal to num + 3.

Expression-oriented & Unit:

Scala is expression-oriented: a function's value is simply its last expression, so the return keyword is usually optional. A function that returns nothing has the type Unit.

def plusThree(num: Int): Int = num + 3   // last expression is the result — no return needed

def greet(name: String): Unit = println(name)  // returns nothing -> Unit

You'll see this in the coding tutorials: the Unit functions just do work, while the value-returning ones simply end with the result.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check