Home »
Scala »
Scala Programs
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]): Unit = {
// Function calling
addAndSubtract(30, 10)
}
// Outer function
def addAndSubtract(num1: Int, num2: Int): Unit = {
// Nested function to add numbers
def add(num1: Int, num2: Int): Int = num1 + num2
// Nested function to subtract numbers
def subtract(num1: Int, num2: Int): Int = num1 - num2
println(s"Addition: ${add(num1, num2)}")
println(s"Subtraction: ${subtract(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 »