File tree Expand file tree Collapse file tree 1 file changed +28
-1
lines changed Expand file tree Collapse file tree 1 file changed +28
-1
lines changed Original file line number Diff line number Diff line change 1
1
---
2
2
layout : tour
3
- title : By-name Parameters
3
+ title : 传名参数
4
4
5
5
discourse : false
6
6
@@ -13,3 +13,30 @@ language: zh-cn
13
13
next-page : annotations
14
14
previous-page : operators
15
15
---
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,这种延迟计算参数直到它被使用时才计算的能力可以帮助提高性能。
You can’t perform that action at this time.
0 commit comments