Home » Scala language

Nested functions in Scala | Usage, and Examples

A function defined inside another function is called a nested function. Scala programming language defines nested functions. In this tutorial, we will learn Scala nested functions with the help of an example.
Submitted by Shivang Yadav, on June 29, 2019

Nested functions in Scala

A nested function is defined as a function which is defined inside the definition of another function. Programming languages like c, java, etc do not support nested functions but Scala does.

In Scala, nesting of functions is possible and there can be multiple function definitions to be called inside the definition of a parent function. This concept of defining a function in the definition of another is called Nesting. Like any other code block, a nested function can also be used to define multiple code definitions inside a function.

The nested function makes it easier to detect the code and increases modularity. Declaring functions inside another function and using it later when on a specific condition makes it more clearly for further development and redesigning the code.


    def function1(){
	    //code block for function 1
	    def function2(){
	        //code block for function 2

Syntax explanation:

The syntax is used to define the nested function in Scala. Definitions of both functions are standard. But the function 2 is defined inside the code of function 1. Which will be called inside the first one only.


object MyClass {
      def factorial(x: Int): Int = {
           def fact(x: Int, accumulator: Int): Int = {
                if (x <= 1) accumulator
                else fact(x - 1, x * accumulator)
            fact(x, 1)
      def main(args: Array[String]) {
         println("factorial of 10 is " + factorial(10));
         println("factorial of 5 is " + factorial(5));

Code from Nested method in Scala


factorial of 10 is 3628800
factorial of 5 is 120

Code explanation:

The above code is to find the factorial of the given number. It uses a nested function i.e. function fact() declared inside the definition of factorial() function.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.