Skip to content

Commit b3df6c9

Browse files
committed
Add Chinese translation of default-parameter-values.
1 parent edadc3e commit b3df6c9

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

_zh-cn/tour/default-parameter-values.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Default Parameter Values
3+
title: 默认参数值
44

55
discourse: false
66

@@ -13,3 +13,37 @@ language: zh-cn
1313
next-page: named-arguments
1414
previous-page: annotations
1515
---
16+
17+
Scala具备给参数提供默认值的能力,这样调用者就可以忽略这些具有默认值的参数。
18+
19+
```tut
20+
def log(message: String, level: String = "INFO") = println(s"$level: $message")
21+
22+
log("System starting") // prints INFO: System starting
23+
log("User not found", "WARNING") // prints WARNING: User not found
24+
```
25+
26+
上面的参数`level`有个默认值,所以是可选的。最后一行中传入的参数`"WARNING"`重写了默认的`"INFO"`。Java中可以重载方法的地方,都可以通过带有可选参数的方法达到同样的效果。不过,调用方只要忽略了一个参数,其他参数必须要带名传入。
27+
28+
```tut
29+
class Point(val x: Double = 0, val y: Double = 0)
30+
31+
val point1 = new Point(y = 1)
32+
```
33+
这里必须带名传入`y = 1`
34+
35+
注意从Java代码中调用时,Scala中的默认参数就不是可选的了,如:
36+
37+
```tut
38+
// Point.scala
39+
class Point(val x: Double = 0, val y: Double = 0)
40+
```
41+
42+
```java
43+
// Main.java
44+
public class Main {
45+
public static void main(String[] args) {
46+
Point point = new Point(1); // does not compile
47+
}
48+
}
49+
```

0 commit comments

Comments
 (0)