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:
Syntax
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
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
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
- Calling the inner function from outside the enclosing function, which fails because it is not visible there.
- Defining the nested function after the code that uses it in a way that references an uninitialised value.
- 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: