Recall & Review
beginner
What is a nullable receiver extension in Kotlin?
An extension function where the receiver type can be null, allowing you to call the function on nullable objects safely.
Click to reveal answer
beginner
How do you declare an extension function with a nullable receiver?
Use a question mark after the receiver type, for example:
fun String?.myExtension() { ... }.Click to reveal answer
beginner
Why are nullable receiver extensions useful?
They let you add functions that can be called on null objects without causing errors, making code safer and cleaner.Click to reveal answer
intermediate
What happens if you call a nullable receiver extension on a null object?
The extension function runs, and inside it, the receiver is null, so you can handle that case safely.
Click to reveal answer
beginner
Example: What does this code print?
fun String?.printLength() {
if (this == null) println("Null string")
else println("Length: ${'$'}{this.length}")
}
fun main() {
val s: String? = null
s.printLength()
}It prints: Null string because the receiver is null and the function checks for that.
Click to reveal answer
How do you declare an extension function with a nullable receiver in Kotlin?
✗ Incorrect
The question mark goes after the receiver type: String?.
What is the receiver inside a nullable receiver extension when called on null?
✗ Incorrect
The receiver is null, so you can check for null inside the extension.
Why use nullable receiver extensions instead of normal extensions?
✗ Incorrect
Nullable receiver extensions allow safe calls on null objects.
Which of these is a valid nullable receiver extension function signature?
✗ Incorrect
The question mark goes after the receiver type to make it nullable.
What will this expression evaluate to?
val s: String? = null s?.length ?: -1
✗ Incorrect
The safe call returns null, so the Elvis operator returns -1.
Explain what a nullable receiver extension is and why it is useful in Kotlin.
Think about calling functions on variables that might be null.
You got /3 concepts.
Write a simple Kotlin extension function with a nullable receiver and explain how it behaves when called on null.
Use fun String?.yourFunction() { ... }
You got /3 concepts.