Nested Functions
In this page:
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
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)))
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: