Skip to content

Add code tabs for _tour/nested-functions #2528

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 16, 2022
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 %}