Skip to content

Commit ab24f32

Browse files
yoleh0tk3y
authored andcommitted
Document that 'this' in infix calls cannot be omitted
1 parent e807fb6 commit ab24f32

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

Diff for: pages/docs/reference/functions.md

+18-3
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ val list = asList(-1, 0, *a, 4)
222222

223223
### Infix notation
224224

225-
Functions can also be called using infix notations when
225+
Functions can also be called using the infix notation (omitting the dot and the parentheses for the call) when
226226

227227
* They are member functions or [extension functions](extensions.html);
228228
* They have a single parameter;
@@ -235,14 +235,29 @@ infix fun Int.shl(x: Int): Int {
235235
}
236236

237237
// call extension function using infix notation
238-
239238
1 shl 2
240239

241240
// is the same as
242-
243241
1.shl(2)
244242
```
245243

244+
Note that infix functions always require both the receiver and the parameter to be specified. When you're
245+
calling a method on the current receiver using the infix notation, you need to use `this` explicitly; unlike regular method calls,
246+
it cannot be omitted. This is required to ensure unambiguous parsing.
247+
248+
```kotlin
249+
class MyStringCollection {
250+
infix fun add(s: String) { /* ... */ }
251+
252+
fun build() {
253+
this add "abc" // Correct
254+
add("abc") // Correct
255+
add "abc" // Incorrect: the receiver must be specified
256+
}
257+
}
258+
```
259+
260+
246261
## Function Scope
247262

248263
In Kotlin functions can be declared at top level in a file, meaning you do not need to create a class to hold a function, like languages such as Java, C# or Scala. In addition

0 commit comments

Comments
 (0)