Challenge - 5 Problems
Nullable Receiver Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nullable receiver extension function call
What is the output of this Kotlin code snippet?
Kotlin
fun String?.greet(): String = this?.let { "Hello, $it!" } ?: "Hello, Guest!" fun main() { val name: String? = null println(name.greet()) }
Attempts:
2 left
💡 Hint
Remember that the extension function handles null receivers with the Elvis operator.
✗ Incorrect
The extension function is defined on a nullable String receiver. When the receiver is null, the Elvis operator returns "Hello, Guest!". Since name is null, the output is "Hello, Guest!".
❓ Predict Output
intermediate2:00remaining
Nullable receiver extension with safe call
What will this Kotlin program print?
Kotlin
fun Int?.doubleOrZero(): Int = this?.times(2) ?: 0 fun main() { val number: Int? = 5 println(number.doubleOrZero()) }
Attempts:
2 left
💡 Hint
Check how the extension function handles non-null receivers.
✗ Incorrect
The receiver is 5 (non-null). The function multiplies it by 2, so the output is 10.
🔧 Debug
advanced2:00remaining
Identify the runtime error in nullable receiver extension
What error will this Kotlin code produce when run?
Kotlin
fun String?.firstChar(): Char = this!!.first() fun main() { val text: String? = null println(text.firstChar()) }
Attempts:
2 left
💡 Hint
Look at the use of the not-null assertion operator (!!) on a null receiver.
✗ Incorrect
The not-null assertion operator (!!) throws NullPointerException if the receiver is null. Here, text is null, so the program crashes with NullPointerException.
📝 Syntax
advanced2:00remaining
Which option correctly defines a nullable receiver extension?
Which of the following Kotlin function definitions correctly declares an extension function with a nullable receiver?
Attempts:
2 left
💡 Hint
Nullable receiver syntax places the question mark after the type name.
✗ Incorrect
Option A correctly places the question mark after String to indicate a nullable receiver. Other options have invalid syntax.
🚀 Application
expert3:00remaining
Result of chaining nullable receiver extensions
Given these Kotlin extension functions, what is the output of the program?
Kotlin
fun String?.trimOrNull(): String? = this?.trim()?.takeIf { it.isNotEmpty() } fun String?.exclaim(): String = this?.let { "$it!" } ?: "No input!" fun main() { val input: String? = " " println(input.trimOrNull().exclaim()) }
Attempts:
2 left
💡 Hint
Consider how trimOrNull returns null for blank strings and how exclaim handles null receivers.
✗ Incorrect
trimOrNull returns null because the trimmed string is empty. Then exclaim returns "No input!" for null receivers.