Introduction to Function Returns in Scala

Welcome, learners! In this unit, we're diving into function return values in Scala programming. Function return values, often simply referred to as "returns," are results given back by a function after performing its assigned task. Let's dive in!

Using Function Returns

Let's create a function that returns a result. Suppose we want our function to perform a calculation — for instance, adding two numbers in a calculator program. Here's how we can write a function that adds two numbers and returns the sum:

This function definition starts with the def keyword followed by the function name (addNumbers), a parameter list in parentheses (num1: Int, num2: Int), and the return type (: Int). The function body follows the = symbol. The value of the last expression in the function (in this case, num1 + num2) is the returned result.

Exploring Data Types in Returns

Returns are not always simple numbers as in the example above. A function can return any type of data from the range Scala supports, including Int, , , , , and . Let's explore this further using the calculation of a circle's area as an example:

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal