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, String, Double, Boolean, Char, and Long. Let's explore this further using the calculation of a circle's area as an example:
In this example, the function circleArea takes a Double parameter named radius and returns a Double representing the area of the circle. The function uses the standard formula for the area of a circle (πr²) with 3.14 as the approximation for π. The return type in this case is not explicitly specified; Scala can infer that the result is a Double based on the expression. However, it can be a good practice to specify the return type explicitly:
Here, the return type is explicitly specified after the colon :. The body of the function calculates the area and returns it as the result.
