You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In Scala it is possible to nest function definitions. The following object provides a `factorial` function for computing the factorial of a given number:
15
15
16
16
```tut
17
-
object FactorialTest extends App {
18
-
def factorial(x: Int): Int = {
17
+
def factorial(x: Int): Int = {
19
18
def fact(x: Int, accumulator: Int): Int = {
20
19
if (x <= 1) accumulator
21
20
else fact(x - 1, x * accumulator)
22
21
}
23
22
fact(x, 1)
24
-
}
25
-
println("Factorial of 2: " + factorial(2))
26
-
println("Factorial of 3: " + factorial(3))
27
-
}
23
+
}
24
+
25
+
println("Factorial of 2: " + factorial(2))
26
+
println("Factorial of 3: " + factorial(3))
28
27
```
29
28
30
29
_Note: the nested function `fact` refers to variable `x` defined in the outer scope as a parameter value of `factorial`._
0 commit comments