0
0
Kotlinprogramming~20 mins

Nullable receiver extensions in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nullable Receiver Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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())
}
ACompilation error
BHello, !
CHello, null!
DHello, Guest!
Attempts:
2 left
💡 Hint
Remember that the extension function handles null receivers with the Elvis operator.
Predict Output
intermediate
2: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())
}
A5
B10
C0
DCompilation error
Attempts:
2 left
💡 Hint
Check how the extension function handles non-null receivers.
🔧 Debug
advanced
2: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())
}
ANullPointerException
BNo error, prints first character
CIndexOutOfBoundsException
DCompilation error
Attempts:
2 left
💡 Hint
Look at the use of the not-null assertion operator (!!) on a null receiver.
📝 Syntax
advanced
2: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?
Afun String?.isEmptyOrNull(): Boolean = this == null || this.isEmpty()
Bfun String.isEmptyOrNull?(): Boolean = this == null || this.isEmpty()
Cfun String.isEmptyOrNull(): Boolean? = this == null || this.isEmpty()
Dfun ?String.isEmptyOrNull(): Boolean = this == null || this.isEmpty()
Attempts:
2 left
💡 Hint
Nullable receiver syntax places the question mark after the type name.
🚀 Application
expert
3: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())
}
A+
B!
CNo input!
DCompilation error
Attempts:
2 left
💡 Hint
Consider how trimOrNull returns null for blank strings and how exclaim handles null receivers.