← Back to Scala Course | Chapter 5: Functions | Lesson 6 of 7

Nested Functions

A nested function is a small helper defined inside a bigger function, like a tool kept inside a toolbox. Only the bigger function can see and use it.

In this page:

  1. Nested Functions
Syntax
scala
def outer(param: Type): ReturnType = {
  def inner(x: Type): ReturnType = {
    // body
  }
  inner(param)
}

Nested Functions

Scala allows defining a function inside another function's body, scoped only to that enclosing function and able to access its parameters and local variables (forming a closure).

This is useful for small helper logic that's only relevant to one specific function, avoiding cluttering the outer scope. Nested functions are a natural consequence of functions being first-class, ordinary values in Scala.

Note: A nested function automatically captures variables from its enclosing function's scope, without needing them passed in explicitly.

Example: Nested Functions

markup
object Main extends App {
  def processNumbers(numbers: List[Int]): Int = {
    def double(n: Int): Int = n * 2
    numbers.map(double).sum
  }

  println(processNumbers(List(1, 2, 3)))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling the inner function from outside the enclosing function, which fails because it is not visible there.
  2. Defining the nested function after the code that uses it in a way that references an uninitialised value.
  3. Copying the same helper into several functions instead of defining it once at a higher level.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.