Home »
Scala
Nested functions in Scala
By IncludeHelp Last updated : October 20, 2024
Nested functions
A nested function is defined as a function which is defined inside the definition of another function. Programming languages like c, java, etc do not support nested functions but Scala does.
In Scala, nesting of functions is possible and there can be multiple function definitions to be called inside the definition of a parent function. This concept of defining a function in the definition of another is called Nesting. Like any other code block, a nested function can also be used to define multiple code definitions inside a function.
The nested function makes it easier to detect the code and increases modularity. Declaring functions inside another function and using it later when on a specific condition makes it more clearly for further development and redesigning the code.
Syntax
def function1(){
//code block for function 1
def function2(){
//code block for function 2
}
}
Syntax explanation
The syntax is used to define the nested function in Scala. Definitions of both functions are standard. But the function 2 is defined inside the code of function 1. Which will be called inside the first one only.
Example of nested function
object MyClass {
def factorial(x: Int): Int = {
def fact(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else fact(x - 1, x * accumulator)
}
fact(x, 1)
}
def main(args: Array[String]) {
println("factorial of 10 is " + factorial(10));
println("factorial of 5 is " + factorial(5));
}
}
Code from Nested method in Scala
Output
factorial of 10 is 3628800
factorial of 5 is 120
Code explanation
The above code is to find the factorial of the given number. It uses a nested function i.e. function fact() declared inside the definition of factorial() function.