Skip to content

Commit 9f48bbf

Browse files
committed
Rewrote by-name parameters section of tour
1 parent 1a5aabb commit 9f48bbf

File tree

2 files changed

+40
-73
lines changed

2 files changed

+40
-73
lines changed

tutorials/tour/_posts/2017-02-13-automatic-closures.md

Lines changed: 0 additions & 73 deletions
This file was deleted.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
---
2+
layout: tutorial
3+
title: By-name Parameters
4+
5+
disqus: true
6+
7+
tutorial: scala-tour
8+
categories: tour
9+
num: 31
10+
next-page: annotations
11+
previous-page: operators
12+
---
13+
14+
_By-name parameters_ are only evaluated when used. They are in contrast to _by-value parameters_. To make a parameter called by-name, simply prepend `=>` to its type.
15+
```tut
16+
def calculate(input: => Int)
17+
```
18+
By-name parameters have the 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.
19+
20+
Here's an example of how we could implement a while loop:
21+
22+
```tut
23+
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
24+
if (condition) {
25+
body
26+
whileLoop(condition)(body)
27+
}
28+
29+
var i = 2
30+
31+
whileLoop (i > 0) {
32+
println(i)
33+
i -= 1
34+
} // prints 2 1
35+
```
36+
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 return type.
37+
38+
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. Here is the output:
39+
40+
This ability to delay evaluation of a parameter until it is used can help performance if the parameter is computationally intensive to evaluate or a longer-running block of code such as fetching a URL.

0 commit comments

Comments
 (0)