Black Friday 2025 – NPI EA (cat = Baeldung on Scala)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Baeldung Pro – Scala – NPI EA (cat = Baeldung on Scala)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.