0
0
Kotlinprogramming~5 mins

Nullable receiver extensions in Kotlin

Choose your learning style9 modes available
Introduction

Nullable receiver extensions let you add functions that work even when the object might be null. This helps avoid crashes and makes your code safer.

You want to add a function to a type that can be null without writing extra null checks every time.
You want to provide a default behavior when the object is null.
You want cleaner code by calling methods directly on nullable objects.
You want to avoid repeating null checks in many places.
You want to extend a class but handle null cases gracefully.
Syntax
Kotlin
fun Type?.functionName() {
    // function body
}

The question mark after the type means the receiver can be null.

You can call this function on both null and non-null objects of that type.

Examples
This function prints the length of a string or says it is null.
Kotlin
fun String?.printLength() {
    if (this == null) {
        println("String is null")
    } else {
        println("Length is ${this.length}")
    }
}
This function returns true if the integer is not null and positive.
Kotlin
fun Int?.isPositive(): Boolean {
    return this != null && this > 0
}
Sample Program

This program defines a nullable receiver extension function describe for String?. It prints a message depending on whether the string is null or not. Then it calls this function on a non-null and a null string.

Kotlin
fun String?.describe() {
    if (this == null) {
        println("This string is null")
    } else {
        println("This string has length ${this.length}")
    }
}

fun main() {
    val name: String? = "Alice"
    val empty: String? = null

    name.describe()
    empty.describe()
}
OutputSuccess
Important Notes

Inside the extension, this refers to the receiver object, which can be null.

Nullable receiver extensions help avoid many explicit null checks outside the function.

Summary

Nullable receiver extensions add functions to types that might be null.

They let you write safer and cleaner code by handling null inside the function.

You call them like normal functions on nullable objects.