Scala Function Nesting

Scala 函数Scala Functions

We can define functions inside Scala functions; functions defined inside functions are called local functions.

In the following example, we implement factorial calculation and use nested functions:

object Test {
   def main(args: Array[String]) {
      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)
   }
}

Executing the above code produces the following output:

$ scalac Test.scala
$ scala Test
1
1
2
6

Scala 函数Scala Functions

Other Extensions