File tree Expand file tree Collapse file tree 1 file changed +35
-1
lines changed Expand file tree Collapse file tree 1 file changed +35
-1
lines changed Original file line number Diff line number Diff line change 11---
22layout : tour
3- title : Default Parameter Values
3+ title : 默认参数值
44
55discourse : false
66
@@ -13,3 +13,37 @@ language: zh-cn
1313next-page : named-arguments
1414previous-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+ ```
You can’t perform that action at this time.
0 commit comments