Q:

Scala program to create nested functions

belongs to collection: Scala User-defined Functions Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to demonstrate the partially applied... >>
<< Scala program to create an anonymous function usin...