Nested Functions
# Scala Nested Functions
[ Scala Functions](#)
We can define functions inside Scala functions. Functions defined inside other functions are called local functions.
In the following example, we implement factorial calculation using a nested function:
object Test { def main(args: Array) { println( factorial(0) ) println( factorial(1) ) println( factorial(2) ) println( factorial(3) ) } def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) }}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test1126
[ Scala Functions](#)
YouTip