How to Use Extension Function with Nullable in Kotlin
In Kotlin, you can define an extension function for a nullable type by adding a question mark after the receiver type, like
fun String?.yourFunction(). This allows you to safely call the function on null or non-null objects, handling null cases inside the function.Syntax
An extension function for a nullable type uses a question mark ? after the receiver type. This means the function can be called on objects that might be null.
- fun: keyword to declare a function
String?: nullable receiver typeyourFunction(): function name and parameters- Inside the function,
thiscan benull, so handle it safely
kotlin
fun String?.printLength() {
if (this == null) {
println("String is null")
} else {
println("Length is ${this.length}")
}
}Example
This example shows how to define and use an extension function on a nullable String?. It safely checks if the string is null before printing its length.
kotlin
fun String?.printLength() {
if (this == null) {
println("String is null")
} else {
println("Length is ${this.length}")
}
}
fun main() {
val name: String? = "Kotlin"
val emptyName: String? = null
name.printLength() // Calls extension on non-null
emptyName.printLength() // Calls extension on null
}Output
Length is 6
String is null
Common Pitfalls
One common mistake is forgetting to mark the receiver type as nullable, which causes the extension function to not accept null values and can lead to crashes.
Also, inside the extension function, you must check for null before accessing properties or methods on this.
kotlin
/* Wrong: receiver is non-nullable, so can't call on null */ fun String.printLengthWrong() { println(this.length) // Unsafe if called on null } /* Right: receiver is nullable and null-safe check */ fun String?.printLengthRight() { if (this == null) { println("String is null") } else { println("Length is ${this.length}") } }
Quick Reference
- Use
Type?as receiver to allow null values. - Always check
thisfornullinside the function. - Call the extension function safely on nullable variables.
Key Takeaways
Mark the receiver type with ? to make the extension function nullable-safe.
Inside the extension, always check if this is null before using it.
Nullable extension functions let you call methods on null objects safely.
For non-nullable receivers, calling on null causes errors.
Use nullable extensions to add safe utilities to nullable types.