在Scala中可以嵌套定义方法。例如以下对象提供了一个factorial方法来计算给定数值的阶乘:

    1. def factorial(x: Int): Int = {
    2. def fact(x: Int, accumulator: Int): Int = {
    3. if (x <= 1) accumulator
    4. else fact(x - 1, x * accumulator)
    5. }
    6. fact(x, 1)
    7. }
    8. println("Factorial of 2: " + factorial(2))
    9. println("Factorial of 3: " + factorial(3))

    程序的输出为:

    1. Factorial of 2: 2
    2. Factorial of 3: 6