Scala function nesting


Release date:2023-11-16 Update date:2023-11-16 Editor:admin View counts:183

Label:

Scala function nesting

We can define the function in the Scala function, and the function defined in the function is called the local function.

In the following example, we implement factorial operations and use embeddedfunctions:

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)
   }
}

Execute the above code, and the output is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).