Latest web development tutorials

Scala nested functions

Scala function Scala function

What I can define a function in Scala function defined functions within a function called local functions.

The following examples we realize factorial operation, and use the built-in 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)
   }
}

Implementation of the above code, the output is:

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

Scala function Scala function