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: docs/topics/extensions.md
+24-9Lines changed: 24 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,29 +14,44 @@ only making new functions callable or new properties accessible using special sy
14
14
Extensions are always called on a receiver. The receiver has to have the same type as the class or interface being extended.
15
15
To use an extension, prefix it with the receiver followed by a `.` and the function or property name.
16
16
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`:
19
19
20
20
```kotlin
21
-
fun String?.orEmpty(): String
21
+
funmain() {
22
+
//sampleStart
23
+
// builder is an instance of StringBuilder
24
+
val builder =StringBuilder()
25
+
// Calls .appendLine() extension function on builder
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?`:
25
41
26
42
```kotlin
27
43
funmain() {
28
-
//sampleStart
29
-
// nullableString is an instance of String?
44
+
// nullableString has type String?
30
45
val nullableString:String?=null
31
46
// Calls .orEmpty() extension function on nullableString
32
47
val nonNullString = nullableString.orEmpty()
33
48
34
-
println("Is the string empty? ${nonNullString ==""}")
49
+
println("Is the string empty? ${nonNullString ==""}")
0 commit comments