Tour of Scala

Nested Methods

Language
Info: JavaScript is currently disabled, code tabs will still work, but preferences will not be remembered.

In Scala it is possible to nest method definitions. The following object provides a factorial method for computing the factorial of a given number:

def factorial(x: Int): Int = {
 def fact(x: Int, accumulator: Int): Int = {
 if (x <= 1) accumulator
 else fact(x - 1, x * accumulator)
 } 
 fact(x, 1)
}
println("Factorial of 2: " + factorial(2))
println("Factorial of 3: " + factorial(3))
def factorial(x: Int): Int =
 def fact(x: Int, accumulator: Int): Int =
 if x <= 1 then accumulator
 else fact(x - 1, x * accumulator)
 fact(x, 1)
println("Factorial of 2: " + factorial(2))
println("Factorial of 3: " + factorial(3))

The output of this program is:

Factorial of 2: 2
Factorial of 3: 6

Contributors to this page:

Contents

AltStyle によって変換されたページ (->オリジナル) /