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:

def addNumbers(num1: Int, num2: Int): Int =
    // This function adds num1 and num2 and returns the sum.
    num1 + num2

@main def run: Unit =
    // Call addNumbers with 5 and 7 as arguments and print the returned value
    println(addNumbers(5, 7)) // Output: 12

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, String, Double, Boolean, Char, and Long. Let's explore this further using the calculation of a circle's area as an example:

def circleArea(radius: Double) = 
    // This function calculates the circle's area and returns it.
    3.14 * radius * radius

@main def run: Unit =
    println(circleArea(5)) // Output: 78.5

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:

def circleArea(radius: Double): Double = 
    3.14 * radius * radius

@main def run: Unit =
    println(circleArea(5)) // Output: 78.5

Here, the return type is explicitly specified after the colon :. The body of the function calculates the area and returns it as the result.

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