@@ -12,22 +12,48 @@ redirect_from: "/tutorials/tour/nested-functions.html"
12
12
13
13
In Scala it is possible to nest method definitions. The following object provides a ` factorial ` method for computing the factorial of a given number:
14
14
15
+ {% tabs Nested_functions_definition class=tabs-scala-version %}
16
+
17
+ {% tab 'Scala 2' for=Nested_functions_definition %}
15
18
``` 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 ))
26
29
```
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 %}
27
47
28
48
The output of this program is:
29
49
50
+ {% tabs Nested_functions_result %}
51
+
52
+ {% tab 'Scala 2 and 3' for=Nested_functions_result %}
30
53
```
31
54
Factorial of 2: 2
32
55
Factorial of 3: 6
33
56
```
57
+ {% endtab %}
58
+
59
+ {% endtabs %}
0 commit comments