Nullable extensions
- Kotlin course
- Intermediate
- Lesson 38/116
- 5 min
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.
Practice 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.
Starter code
// Define the String?.shoutOrEmpty nullable extension
// null-safe uppercase or empty string
// print both filled and null values in mainSample solution
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
fun main() {
println("hi".shoutOrEmpty())
val s: String? = null
println(s.shoutOrEmpty())
}Expected output
HI
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the nullable extension definition
fun String____.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
fun String?.shoutOrEmpty(): String {
return this?.uppercase() ?: ""
}
Explanation: String? is a nullable receiver type.
2 Match the nullable extension parts
| Term | Meaning |
|---|---|
String? |
Nullable receiver |
this?.uppercase() |
Safe call |
?: "" |
Elvis operator |
null.shoutOrEmpty() |
Null call |
3 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 Correct answer
- Only for String literals
- In abstract classes
Explanation: A nullable extension can be called on both null and non-null values.