diff --git a/_tour/by-name-parameters.md b/_tour/by-name-parameters.md index 6d0ff8b610..b8318783f4 100644 --- a/_tour/by-name-parameters.md +++ b/_tour/by-name-parameters.md @@ -11,13 +11,21 @@ redirect_from: "/tutorials/tour/by-name-parameters.html" --- _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. + +{% tabs by-name-parameters_1 %} +{% tab 'Scala 2 and 3' for=by-name-parameters_1 %} ```scala mdoc def calculate(input: => Int) = input * 37 ``` +{% endtab %} +{% endtabs %} + 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. Here's an example of how we could implement a while loop: +{% tabs by-name-parameters_2 class=tabs-scala-version %} +{% tab 'Scala 2' for=by-name-parameters_2 %} ```scala mdoc def whileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { @@ -32,6 +40,24 @@ whileLoop (i > 0) { i -= 1 } // prints 2 1 ``` +{% endtab %} +{% tab 'Scala 3' for=by-name-parameters_2 %} +```scala +def whileLoop(condition: => Boolean)(body: => Unit): Unit = + if condition then + body + whileLoop(condition)(body) + +var i = 2 + +whileLoop (i > 0) { + println(i) + i -= 1 +} // prints 2 1 +``` +{% endtab %} +{% endtabs %} + 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`. 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.