Scala - Nested Functions


Advertisements

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.

scala_functions.htm

Useful Video Courses


Video

Scala Online Training

82 Lectures 7 hours

Arnab Chakraborty

Video

Apache Spark with Scala - Hands On with Big Data

23 Lectures 1.5 hours

Mukund Kumar Mishra

Video

Delta Lake with Apache Spark using Scala

52 Lectures 1.5 hours

Bigdata Engineer

Video

Apache Spark with Scala useful for Databricks Certification

76 Lectures 5.5 hours

Bigdata Engineer

Video

Machine Learning with Apache Spark 3.0 using Scala

69 Lectures 7.5 hours

Bigdata Engineer

Advertisements