Scala supports nested methods, which are methods defined inside another method definition.
def method_1(): Unit = {
def method_2(): Unit = {
// statements for inner method
}
// statements for outer method
method_2()
}
Nesting methods in Scala can be done in two ways:
Single nesting - one method definition inside another.
Multiple nesting - more than one method definitions inside a method.
Implementation of nested functions has some positive effects on a code, including:
object SingleNest {def factorial(i: Int): Int = {// outer methoddef inner_fact(i: Int, num: Int): Int = {// inner methodif (i <= 1)numelseinner_fact(i - 1, i * num)}inner_ fact(i, 1)}def main(args: Array[String]): Unit = {println( factorial(6) )}}
The above code snippet for factorial is a good example of the single nested method.
The other method factorial()
involves an inner method fact()
that processes the given input in def main()
and returns the result.
object MultiMested {def function() = {var a = 10var b = 30addition()def addition() = { // method 01println("sum = " + (a + b))subtraction()def subtraction() = { // method 02println("subtraction = " + (b - a))multiplication()def multiplication() = { // method 03println("multiplication = " + (a * b))}}}}def main(args: Array[String]): Unit = {function()}}
The above code snippet involves three nested methods inside the
function()
method.
The first inner method performs addition()
, which then calls the second method subtraction()
. subtraction()
then performs multiplication()
on variables declared in function()
and displays output, respectively.
Free Resources