What are nested methods in Scala?

Scala supports nested methods, which are methods defined inside another method definition.

Syntax


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.

Single vs Multiple Nesting

Advantages

Implementation of nested functions has some positive effects on a code, including:

  • Increasing code modularity
  • Increasing readability of code
  • Redesigning of code becomes easier

Code

Example 01 - Single nested method

object SingleNest {
def factorial(i: Int): Int = {
// outer method
def inner_fact(i: Int, num: Int): Int = {
// inner method
if (i <= 1)
num
else
inner_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.

Example 02 - Multiple Nesting

object MultiMested {
def function() = {
var a = 10
var b = 30
addition()
def addition() = { // method 01
println("sum = " + (a + b))
subtraction()
def subtraction() = { // method 02
println("subtraction = " + (b - a))
multiplication()
def multiplication() = { // method 03
println("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

Copyright ©2025 Educative, Inc. All rights reserved