Skip to content

Commit c835ff2

Browse files
authored
Clarify default params and named args corner cases
1 parent b8ae40c commit c835ff2

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

pages/docs/reference/functions.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,23 @@ class B : A() {
9191
}
9292
```
9393

94+
If a default parameter precedes a parameter with no default value, the default value can be used only by calling the function with [named arguments](#named-arguments):
95+
96+
``` kotlin
97+
fun foo(bar: Int = 0, baz: Int) { /* ... */ }
98+
99+
foo(baz = 1) // The default value bar = 0 is used
100+
```
101+
102+
But if a last argument [lambda](lambdas.html#lambda-expression-syntax) is passed to a function call outside the parentheses, passing no values for the default parameters is allowed:
103+
104+
``` kotlin
105+
fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { /* ... */ }
106+
107+
foo(1) { println("hello") } // Uses the default value baz = 1
108+
foo { println("hello") } // Uses both defeault values bar = 0 and baz = 1
109+
```
110+
94111
### Named Arguments
95112

96113
Function parameters can be named when calling functions. This is very convenient when a function has a high number of parameters or default ones.
@@ -136,10 +153,20 @@ and if we do not need all arguments
136153
reformat(str, wordSeparator = '_')
137154
```
138155

156+
When a function is called with both positional and named arguments, all the positional arguments should be placed before the first named one. For example, the call `f(1, y = 2)` is allowed, but `f(x = 1, 2)` is not.
157+
158+
[Variable number of arguments (*vararg*{: .keyword })](#variable-number-of-arguments-varargs) can be passed in the named form by using the **spread** operator:
159+
160+
``` kotlin
161+
fun foo(vararg strings: String) { /* ... */ }
162+
163+
foo(strings = *arrayOf("a", "b", "c"))
164+
foo(strings = "a") // Not required for a single value
165+
```
166+
139167
Note that the named argument syntax cannot be used when calling Java functions, because Java bytecode does not
140168
always preserve names of function parameters.
141169

142-
143170
### Unit-returning functions
144171

145172
If a function does not return any useful value, its return type is `Unit`. `Unit` is a type with only one value - `Unit`. This

0 commit comments

Comments
 (0)