Nullable receiver extensions in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code with nullable receiver extensions changes as the input size grows.
Specifically, how does calling an extension function on a nullable object affect performance when used repeatedly?
Analyze the time complexity of the following code snippet.
fun String?.countChars(): Int {
return this?.length ?: 0
}
fun totalChars(list: List): Int {
var sum = 0
for (item in list) {
sum += item.countChars()
}
return sum
}
This code defines an extension function on a nullable String and sums the lengths of all strings in a list, safely handling nulls.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list and calling the nullable extension function.
- How many times: Once for each element in the list (n times).
Each element in the list causes one call to the extension function, which does a simple check and returns length or zero.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to countChars() |
| 100 | About 100 calls to countChars() |
| 1000 | About 1000 calls to countChars() |
Pattern observation: The number of operations grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to run grows linearly with the number of elements in the list.
[X] Wrong: "Nullable receiver extensions add extra hidden loops or slow down the code exponentially."
[OK] Correct: The extension function runs once per element and does a simple check, so it only adds a small constant time per call, not extra loops.
Understanding how nullable extensions behave helps you write safe and efficient Kotlin code, a skill valued in many coding challenges and real projects.
What if we changed the list to a nested list of nullable strings? How would the time complexity change?
Practice
nullable receiver extensions in Kotlin?Solution
Step 1: Understand nullable receiver extensions
Nullable receiver extensions let you add functions to types that can be null, so you can call these functions safely without extra null checks.Step 2: Identify the benefit
This means you can write cleaner code by calling functions directly on nullable objects without risking null pointer exceptions.Final Answer:
They allow calling functions on nullable types without explicit null checks. -> Option DQuick Check:
Nullable receiver extensions = call on nullable safely [OK]
- Thinking they convert nullable to non-nullable permanently
- Assuming they prevent null assignments
- Confusing with regular extensions on non-null types
isNullOrEmpty for String? in Kotlin?Solution
Step 1: Identify nullable receiver syntax
To define an extension on a nullable type, useString?as the receiver type with a question mark after the type name.Step 2: Check function syntax
The function name should not have a question mark. Sofun String?.isNullOrEmpty()is correct.Final Answer:
fun String?.isNullOrEmpty(): Boolean = this == null || this.isEmpty() -> Option CQuick Check:
Nullable receiver = question mark after type [OK]
- Putting ? after function name instead of receiver type
- Missing ? on receiver type for nullable
- Using non-nullable receiver for nullable extension
fun String?.describe(): String = this ?: "Empty"
fun main() {
val text1: String? = "Hello"
val text2: String? = null
println(text1.describe())
println(text2.describe())
}Solution
Step 1: Understand the extension function behavior
The function returns the string itself if not null, otherwise returns "Empty".Step 2: Apply to variables
text1 is "Hello", so describe() returns "Hello". text2 is null, so describe() returns "Empty".Final Answer:
Hello\nEmpty -> Option AQuick Check:
Nullable describe returns value or "Empty" [OK]
- Assuming null prints as "null" string
- Confusing ?: with !! operator
- Expecting function to throw on null
fun String?.firstChar(): Char = this[0]
fun main() {
val s: String? = null
println(s.firstChar())
}Solution
Step 1: Analyze extension function code
The function callsthis[0]on a nullable receiverString?without a null check or safe call.Step 2: Understand compiler behavior
Kotlin compiler detects the unsafe access on nullable receiver and produces a compilation error.Final Answer:
Compilation error: Cannot call get(0) on nullable receiver without null check -> Option BQuick Check:
Unsafe access on nullable receiver = compile error [OK]
- Assuming nullable receiver is auto-checked
- Thinking it causes runtime exception instead of compilation error
- Thinking it compiles and prints null instead of error
safeLength() for String? that returns the string length or zero if null. Which implementation is correct and safe?1) fun String?.safeLength() = this.length ?: 0 2) fun String?.safeLength() = this?.length ?: 0 3) fun String.safeLength() = this.length ?: 0 4) fun String?.safeLength() = if (this == null) null else this.length
Solution
Step 1: Check each option for null safety
Option 1 callsthis.lengthdirectly on nullablethis, causing error. Option 3 uses non-nullable receiver, so not valid for nullable. Option 4 returns null instead of Int zero.Step 2: Identify correct safe call usage
Option 2 uses safe callthis?.lengthwhich returns length or null, then ?: 0 returns zero if null. This is safe and returns Int.Final Answer:
fun String?.safeLength() = this?.length ?: 0 -> Option AQuick Check:
Safe call ?. with ?: zero fallback is correct pattern [OK]
- Calling length directly on nullable without safe call
- Using non-nullable receiver for nullable extension
- Returning null instead of zero for null input
Ready to prove it?
Pass the test and this pattern moves unknown
