In this guide, we will discuss Scala Nested Functions. Scala allows you to define functions inside a function and functions defined inside other functions are called local functions. Here is an implementation of a factorial calculator, where we use a conventional technique of calling a second, nested method to do the work.
Try the following program to implement nested functions.
Example
object Demo { 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) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
1 1 2 6
Like a local variable declaration in many languages, a nested method is only visible inside the enclosing method. If you try to call fact() outside of factorial(), you will get a compiler error.
Next Topic : Click Here
Pingback: Scala - Default Parameter Values for a Function | Adglob
Pingback: Scala - Functions | Adglob Infosystem Pvt Ltd