@@ -12,22 +12,48 @@ redirect_from: "/tutorials/tour/nested-functions.html"
1212
1313In Scala it is possible to nest method definitions. The following object provides a ` factorial ` method for computing the factorial of a given number:
1414
15+ {% tabs Nested_functions_definition class=tabs-scala-version %}
16+
17+ {% tab 'Scala 2' for=Nested_functions_definition %}
1518``` scala mdoc
16- def factorial (x : Int ): Int = {
17- def fact (x : Int , accumulator : Int ): Int = {
18- if (x <= 1 ) accumulator
19- else fact(x - 1 , x * accumulator)
20- }
21- fact(x, 1 )
22- }
23-
24- println(" Factorial of 2: " + factorial(2 ))
25- println(" Factorial of 3: " + factorial(3 ))
19+ def factorial (x : Int ): Int = {
20+ def fact (x : Int , accumulator : Int ): Int = {
21+ if (x <= 1 ) accumulator
22+ else fact(x - 1 , x * accumulator)
23+ }
24+ fact(x, 1 )
25+ }
26+
27+ println(" Factorial of 2: " + factorial(2 ))
28+ println(" Factorial of 3: " + factorial(3 ))
2629```
30+ {% endtab %}
31+
32+ {% tab 'Scala 3' for=Nested_functions_definition %}
33+ ``` scala
34+ def factorial (x : Int ): Int =
35+ def fact (x : Int , accumulator : Int ): Int =
36+ if x <= 1 then accumulator
37+ else fact(x - 1 , x * accumulator)
38+ fact(x, 1 )
39+
40+ println(" Factorial of 2: " + factorial(2 ))
41+ println(" Factorial of 3: " + factorial(3 ))
42+
43+ ```
44+ {% endtab %}
45+
46+ {% endtabs %}
2747
2848The output of this program is:
2949
50+ {% tabs Nested_functions_result %}
51+
52+ {% tab 'Scala 2 and 3' for=Nested_functions_result %}
3053```
3154Factorial of 2: 2
3255Factorial of 3: 6
3356```
57+ {% endtab %}
58+
59+ {% endtabs %}
0 commit comments