In Scala, if a method is defined inside another method, the inner method is called nested inside the outer method or it is called the Nested method.

The following example provides a factorial method for computing the factorial of a given number. Save the program with nestedmethod.scala name and run it from the terminal by using scala nestedmethod.scala command (refer screenshot).

def nestedmethod(x: Int): Int = { def fact(x: Int, accumulator: Int): Int = { if (x <= 1) accumulator else fact(x - 1, x * accumulator) } fact(x, 1) } println("Factorial of 2: " + nestedmethod(2)) println("Factorial of 3: " + nestedmethod(3))

Output

nestedmethod_example

Click Here To Download Code File.