Skip to content

Rewrote by-name parameters section of tour #757

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
May 12, 2017
Merged
Show file tree
Hide file tree
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
73 changes: 0 additions & 73 deletions tutorials/tour/_posts/2017-02-13-automatic-closures.md

This file was deleted.

40 changes: 40 additions & 0 deletions tutorials/tour/_posts/2017-02-13-by-name-parameters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
layout: tutorial
title: By-name Parameters

disqus: true

tutorial: scala-tour
categories: tour
num: 31
next-page: annotations
previous-page: operators
---

_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.
```tut
def calculate(input: => Int) = input * 37
```
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.

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

```tut
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
whileLoop(condition)(body)
}

var i = 2

whileLoop (i > 0) {
println(i)
i -= 1
} // prints 2 1
```
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.

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.