1. Introduction

Scala supports the usage of nested functions. Nested functions are those that are defined within another function. In this short article, let’s look at nested functions and why they are useful.

2. Writing a Nested Function

Let’s write a function to calculate the factorial of a given number using recursion. We can use a nested function for the factorial calculation:

def factorial(num:Int): Int = {
  def recursiveFactorial(num: Int): Int = {
    num match {
      case i if i <= 0 => throw new Exception("Enter number > 0")
      case 1 => 1
      case n => n * recursiveFactorial(num-1)
    }
  }
  recursiveFactorial(num)
}

Here, we’ve defined the function recursiveFactorial() as a nested function within factorial(). Hence, the scope of the function recursiveFactorial() is local to the function factorial().

3. Advantages of Nested Functions

Some of the advantages of using nested functions are:

  • Provides better modularity of the code
  • Improves readability of bigger methods
  • Provides proper scoping of one-time used functions

We can achieve the functionality by moving the function recursiveFactorial() outside factorial() and making it private. However, this would make the recursiveFactorial() method accessible to all the other methods within the same class where it is defined. By making it nested, we can restrict the usage of this function.

4. How Does the Scala Compiler Synthesize Nested Functions?

During compilation, the Scala compiler will rearrange the nested functions and move them to the same level as the function where it is defined. Moreover, to avoid any name conflicts, the compiler will suffix with the $ symbol. We can inspect the generated method names by using the command:

scalac -Xprint:genBCode Factorial.scala

The Scala compiler will rename the function recursiveFactorial() to recursiveFactorial$1 and move it to the same level as factorial(). If we define another nested function with the same name, the Scala compiler will name it as recursiveFactorial$2().

5. Conclusion

In this article, we looked at nested functions in Scala and how to use them. As always, the sample code used in this tutorial is available over on GitHub.