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!
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.
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:
