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

Nested Functions

In this page:

  1. Nested Functions

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)))
}
🔒

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.