Skip to content

Commit cafaecd

Browse files
authored
Merge pull request #1208 from realwunan/by-name-parameters
Simplify Chinese translation of Scala Tour: by-name-parameters.md
2 parents 9ddbc29 + 8fcc7cd commit cafaecd

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

_zh-cn/tour/by-name-parameters.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: By-name Parameters
3+
title: 传名参数
44

55
discourse: false
66

@@ -13,3 +13,30 @@ language: zh-cn
1313
next-page: annotations
1414
previous-page: operators
1515
---
16+
17+
_传名参数_ 仅在被使用时触发实际参数的求值运算。 它们与 _传值参数_ 正好相反。 要将一个参数变为传名参数,只需在它的类型前加上 `=>`
18+
```tut
19+
def calculate(input: => Int) = input * 37
20+
```
21+
传名参数的优点是,如果它们在函数体中未被使用,则不会对它们进行求值。 另一方面,传值参数的优点是它们仅被计算一次。
22+
以下是我们如何实现一个 while 循环的例子:
23+
24+
```tut
25+
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
26+
if (condition) {
27+
body
28+
whileLoop(condition)(body)
29+
}
30+
31+
var i = 2
32+
33+
whileLoop (i > 0) {
34+
println(i)
35+
i -= 1
36+
} // prints 2 1
37+
```
38+
方法 `whileLoop` 使用多个参数列表来分别获取循环条件和循环体。 如果 `condition` 为 true,则执行 `body`,然后对 whileLoop 进行递归调用。 如果 `condition` 为 false,则永远不会计算 body,因为我们在 `body` 的类型前加上了 `=>`
39+
40+
现在当我们传递 `i > 0` 作为我们的 `condition` 并且 `println(i); i-= 1` 作为 `body` 时,它表现得像许多语言中的标准 while 循环。
41+
42+
如果参数是计算密集型或长时间运行的代码块,如获取 URL,这种延迟计算参数直到它被使用时才计算的能力可以帮助提高性能。

0 commit comments

Comments
 (0)