Skip to content

Commit 7d18cd2

Browse files
committed
receiver section update
1 parent fda43a4 commit 7d18cd2

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

docs/topics/extensions.md

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,26 @@ 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
22-
```
23-
24-
So in this case, the receiver is a `String?` instance, and the _receiver type_ is `String?`:
25-
26-
```kotlin
27-
fun main() {
21+
fun main() {
2822
//sampleStart
29-
// nullableString is an instance of String?
30-
val nullableString: String? = null
31-
// Calls .orEmpty() extension function on nullableString
32-
val nonNullString = nullableString.orEmpty()
33-
34-
println("Is the string empty? ${nonNullString == ""}")
35-
// Is the string empty? true
36-
//sampleEnd
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
3733
}
34+
//sampleEnd
3835
```
39-
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-extension-function-isorempty"}
36+
{kotlin-runnable="true" kotlin-min-compiler-version="1.3" id="kotlin-extension-function-stringbuilder"}
4037

4138
## Extension functions
4239

@@ -123,8 +120,8 @@ returns a non-null value.
123120
### Generic extension functions
124121

125122
To create generic extension functions, declare the generic type parameter before the function name
126-
to make it available in the receiver type expression. In this example, the `.endpoints()` function extends a `List<T>`
127-
class where `T` can be any type:
123+
to make it available in the receiver type expression. In this example, the `.endpoints()` function extends `List<T>`
124+
where `T` can be any type:
128125

129126
```kotlin
130127
fun <T> List<T>.endpoints(): Pair<T, T> {

0 commit comments

Comments
 (0)