Kotlin
Nullable extensions
Learn extension functions with nullable receivers.
Nullable extension
A nullable extension is an extension function whose receiver is nullable. It is written as fun Type?.method() and can be called even on null.
Example: fun String?.shoutOrEmpty(): String { return this?.uppercase() ?: "" }. This function can be called on both String and null. Calling "hi".shoutOrEmpty() returns HI; calling null.shoutOrEmpty() returns "". A nullable extension puts null handling in one place; it is convenient for null-safe helpers.
The shoutOrEmpty function
Inside a nullable extension body, this is nullable. You call methods with this?.method() and provide a default with ?:.
Example: fun String?.shoutOrEmpty(): String { return this?.uppercase() ?: "" }. this?.uppercase() uppercases when this is not null, and returns null otherwise. ?: "" gives an empty string when null. Calling "hi".shoutOrEmpty() returns HI; calling null.shoutOrEmpty() returns "". A nullable extension is a short way to write null-safe helpers.
Exercise The String?.shoutOrEmpty extension
Define an extension function fun String?.shoutOrEmpty(): String whose body returns this?.uppercase() ?: "". In main print the result of "hi".shoutOrEmpty() and, after declaring val s: String? = null, the result of s.shoutOrEmpty() on separate lines with println.
Show example solution
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
fun main() {
println("hi".shoutOrEmpty())
val s: String? = null
println(s.shoutOrEmpty())
}
Test yourself
-
Complete the nullable extension definition
fun String____.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
Show answer
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
-
Match the nullable extension parts
- String?
- Nullable receiver
- this?.uppercase()
- Safe call
- ?: ""
- Elvis operator
- null.shoutOrEmpty()
- Null call
-
When is the nullable extension <code>fun String?.shoutOrEmpty()</code> useful?
- Only for non-null values
- When it can be called on both null and non-null values
- Only for String literals
- In abstract classes
Show answer
When it can be called on both null and non-null values — A nullable extension can be called on both null and non-null values.
Next lesson: companion extensions