Skip to content

Commit e0e4289

Browse files
authored
Add code tabs for _tour/by-name-parameters (#2564)
1 parent a5a5cc6 commit e0e4289

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: _tour/by-name-parameters.md

+26
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,21 @@ redirect_from: "/tutorials/tour/by-name-parameters.html"
1111
---
1212

1313
_By-name parameters_ are evaluated every time they are used. They won't be evaluated at all if they are unused. This is similar to replacing the by-name parameters with the passed expressions. They are in contrast to _by-value parameters_. To make a parameter called by-name, simply prepend `=>` to its type.
14+
15+
{% tabs by-name-parameters_1 %}
16+
{% tab 'Scala 2 and 3' for=by-name-parameters_1 %}
1417
```scala mdoc
1518
def calculate(input: => Int) = input * 37
1619
```
20+
{% endtab %}
21+
{% endtabs %}
22+
1723
By-name parameters have the advantage that they are not evaluated if they aren't used in the function body. On the other hand, by-value parameters have the advantage that they are evaluated only once.
1824

1925
Here's an example of how we could implement a while loop:
2026

27+
{% tabs by-name-parameters_2 class=tabs-scala-version %}
28+
{% tab 'Scala 2' for=by-name-parameters_2 %}
2129
```scala mdoc
2230
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
2331
if (condition) {
@@ -32,6 +40,24 @@ whileLoop (i > 0) {
3240
i -= 1
3341
} // prints 2 1
3442
```
43+
{% endtab %}
44+
{% tab 'Scala 3' for=by-name-parameters_2 %}
45+
```scala
46+
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
47+
if condition then
48+
body
49+
whileLoop(condition)(body)
50+
51+
var i = 2
52+
53+
whileLoop (i > 0) {
54+
println(i)
55+
i -= 1
56+
} // prints 2 1
57+
```
58+
{% endtab %}
59+
{% endtabs %}
60+
3561
The method `whileLoop` uses multiple parameter lists to take a condition and a body of the loop. If the `condition` is true, the `body` is executed and then a recursive call to whileLoop is made. If the `condition` is false, the body is never evaluated because we prepended `=>` to the type of `body`.
3662

3763
Now when we pass `i > 0` as our `condition` and `println(i); i-= 1` as the `body`, it behaves like the standard while loop in many languages.

0 commit comments

Comments
 (0)