You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _tour/named-arguments.md
+19-7
Original file line number
Diff line number
Diff line change
@@ -20,26 +20,38 @@ When calling methods, you can label the arguments with their parameter names lik
20
20
{% tab 'Scala 2 and 3' for=named-arguments-when-good %}
21
21
```scala mdoc
22
22
defprintName(first: String, last: String):Unit=
23
-
println(first +""+last)
23
+
println(s"$first$last")
24
24
25
-
printName("John", "Smith") // Prints "John Smith"
26
-
printName(first ="John", last ="Smith") // Prints "John Smith"
27
-
printName(last ="Smith", first ="John") // Prints "John Smith"
25
+
printName("John", "Public") // Prints "John Public"
26
+
printName(first ="John", last ="Public") // Prints "John Public"
27
+
printName(last ="Public", first ="John") // Prints "John Public"
28
+
printName("Elton", last ="John") // Prints "Elton John"
28
29
```
29
30
{% endtab %}
30
31
31
32
{% endtabs %}
32
33
33
-
Notice how the order of named arguments can be rearranged. However, if some arguments are named and others are not, the unnamed arguments must come first and in the order of their parameters in the method signature.
34
+
This is useful when two parameters have the same type and the arguments could be accidentally swapped.
35
+
36
+
Notice that named arguments can be written in any order. However, once the arguments are not in parameter order, reading from left to right, then the rest of the arguments must be named.
37
+
38
+
In the following example, named arguments enable the middle parameter to be omitted. But in the error case, the first argument is out of order, so the second argument must be named.
34
39
35
40
{% tabs named-arguments-when-error %}
36
41
37
42
{% tab 'Scala 2 and 3' for=named-arguments-when-error %}
38
43
```scala mdoc:fail
39
-
printName(last ="Smith", "john") // error: positional after named argument
0 commit comments