Skip to content

Commit 792b7b5

Browse files
committed
receiver section update
1 parent fda43a4 commit 792b7b5

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

docs/topics/extensions.md

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,44 @@ only making new functions callable or new properties accessible using special sy
1414
Extensions are always called on a receiver. The receiver has to have the same type as the class or interface being extended.
1515
To use an extension, prefix it with the receiver followed by a `.` and the function or property name.
1616

17-
For example, the [`.orEmpty()`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/or-empty.html) extension function
18-
from the standard library extends the `String?` class:
17+
For example, the [`.appendLine()`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/or-empty.html) extension function from the standard library extends the `StringBuilder` class.
18+
So in this case, the receiver is a `StringBuilder` instance, and the _receiver type_ is `StringBuilder`:
1919

2020
```kotlin
21-
fun String?.orEmpty(): String
21+
fun main() {
22+
//sampleStart
23+
// builder is an instance of StringBuilder
24+
val builder = StringBuilder()
25+
// Calls .appendLine() extension function on builder
26+
.appendLine("Hello")
27+
.appendLine()
28+
.appendLine("World")
29+
println(builder.toString())
30+
// Hello
31+
//
32+
// World
33+
}
34+
//sampleEnd
2235
```
36+
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-extension-function-stringbuilder"}
2337

24-
So in this case, the receiver is a `String?` instance, and the _receiver type_ is `String?`:
38+
The receiver can also be a type. For example, the standard library has the [`.orEmpty()`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/or-empty.html) extension function,
39+
which extends the nullable `String?` type. In this case, the receiver is the `nullableString` variable with `String?` type,
40+
and the receiver type is `String?`:
2541

2642
```kotlin
2743
fun main() {
28-
//sampleStart
29-
// nullableString is an instance of String?
44+
// nullableString has type String?
3045
val nullableString: String? = null
3146
// Calls .orEmpty() extension function on nullableString
3247
val nonNullString = nullableString.orEmpty()
3348

34-
println("Is the string empty? ${nonNullString == ""}")
49+
println("Is the string empty? ${nonNullString == ""}")
3550
// Is the string empty? true
36-
//sampleEnd
3751
}
52+
//sampleEnd
3853
```
39-
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-extension-function-isorempty"}
54+
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-extension-function-orempty"}
4055

4156
## Extension functions
4257

0 commit comments

Comments
 (0)