Scala program to create nested functions

Here, we are going to learn how to create nested functions in Scala programming language?
Submitted by Nidhi, on May 28, 2021 [Last updated : March 09, 2023]

Scala – Create Nested Functions

Here, we will define nested functions within a function to calculate the addition and subtraction of two integer numbers.

Scala code to create nested functions

The source code to create nested functions is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a nested function.

object Sample {
  def main(args: Array[String]) {
    //Function calling
    AddAndSubtract(30, 10);
  }

  def AddAndSubtract(num1: Int, num2: Int) {
    def Add(num1: Int, num2: Int): Int = {
      return (num1 + num2);
    }

    def Sub(num1: Int, num2: Int): Int = {
      return (num1 - num2);
    }

    printf("Addition: %d\n", Add(num1, num2));
    printf("Subtraction: %d\n", Sub(num1, num2));
  }
}

Output

Addition: 40
Subtraction: 20

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

Here, we defined a function AddAndSubtract() that contains the definition of two nested functions Add() and Sub(). And, we calculated the addition and subtraction of integer numbers and printed the result on the console screen.

In the main() function, we called AddAndSubtract() function with value 30, 10 to perform addition and subtraction operation.

Scala User-defined Functions Programs »





Comments and Discussions!

Load comments ↻





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