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

Problem Solution:

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

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));


Addition: 40
Subtraction: 20


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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.