Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 36 additions & 10 deletions _tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,48 @@ redirect_from: "/tutorials/tour/nested-functions.html"

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

{% tabs Nested_functions_definition class=tabs-scala-version %}

{% tab 'Scala 2' for=Nested_functions_definition %}
```scala mdoc
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) accumulator
else fact(x - 1, x * accumulator)
}
fact(x, 1)
}

println("Factorial of 2: " + factorial(2))
println("Factorial of 3: " + factorial(3))
```
{% endtab %}

{% tab 'Scala 3' for=Nested_functions_definition %}
```scala
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))

```
{% endtab %}

{% endtabs %}

The output of this program is:

{% tabs Nested_functions_result %}

{% tab 'Scala 2 and 3' for=Nested_functions_result %}
```
Factorial of 2: 2
Factorial of 3: 6
```
{% endtab %}

{% endtabs %}