0
0
Kotlinprogramming~5 mins

Nullable receiver extensions in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afun String.myFunc() { }
Bfun String.myFunc?() { }
Cfun ?String.myFunc() { }
Dfun String?.myFunc() { }
What is the receiver inside a nullable receiver extension when called on null?
AIt is null
BIt throws an exception
CIt is an empty string
DIt is a default value
Why use nullable receiver extensions instead of normal extensions?
ATo override existing functions
BTo safely call functions on nullable objects without errors
CTo avoid using null checks outside
DTo make functions faster
Which of these is a valid nullable receiver extension function signature?
Afun ?Int.isPositive() = this > 0
Bfun Int.isPositive?() = this > 0
Cfun Int?.isPositive() = this != null && this > 0
Dfun Int.isPositive() = this != null
What will this expression evaluate to?
val s: String? = null
s?.length ?: -1
A-1
B0
Cnull
DThrows NullPointerException
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.