Safe call operator (?.) in Kotlin - Time & Space Complexity
We want to understand how using the safe call operator affects the time it takes for code to run.
Specifically, does checking for null with ?. change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
fun printNameLength(name: String?) {
val length = name?.length
println(length)
}
fun printAllLengths(names: List) {
for (name in names) {
printNameLength(name)
}
}
This code prints the length of each name in a list, safely handling null names using the safe call operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each name in the list.
- How many times: Once for each item in the list (n times).
Each name is checked once with the safe call operator, which is a quick null check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 null checks and length retrievals |
| 100 | About 100 null checks and length retrievals |
| 1000 | About 1000 null checks and length retrievals |
Pattern observation: The work grows directly with the number of names. More names mean more checks, but each check is simple and fast.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the list.
[X] Wrong: "Using the safe call operator makes the code slower by a lot because it adds extra checks inside the loop."
[OK] Correct: The safe call operator adds only a simple null check per item, which is very fast and does not change the overall growth pattern.
Understanding how small language features like the safe call operator affect performance helps you write clear and efficient code, a skill valued in many coding discussions.
"What if we replaced the safe call operator with a manual if-check inside the loop? How would the time complexity change?"
Practice
?. do in Kotlin?Solution
Step 1: Understand the purpose of the safe call operator
The safe call operator?.is used to safely access properties or call functions on objects that might be null.Step 2: Behavior when object is null
If the object is null, the operator returns null instead of throwing an error or crashing the program.Final Answer:
It accesses a property or calls a function only if the object is not null. -> Option CQuick Check:
Safe call operator = Access if not null [OK]
- Thinking it crashes on null
- Confusing with non-null assertion operator (!!)
- Assuming it provides default values
length property of a nullable String name?Solution
Step 1: Identify the safe call syntax
The safe call operator is?., used asobject?.propertyorobject?.function().Step 2: Check each option
val len = name.length uses.without safety, which can cause a crash ifnameis null. val len = name?.length correctly uses?.. val len = name!!length uses!!incorrectly with property access. val len = name?length uses invalid syntax?length.Final Answer:
val len = name?.length -> Option BQuick Check:
Safe call syntax = ?. [OK]
- Using . without safe call on nullable
- Confusing !! with ?.
- Writing invalid syntax like ?property
val text: String? = null println(text?.length)
Solution
Step 1: Analyze the nullable variable
The variabletextis null, so accessingtext?.lengthuses the safe call operator.Step 2: Evaluate the safe call result
Sincetextis null,text?.lengthreturns null instead of crashing or returning 0.Final Answer:
null -> Option DQuick Check:
Null safe call on null = null [OK]
- Expecting 0 as length of null
- Thinking it throws an exception
- Assuming empty string output
val user: User? = null val nameLength = user.length?.toString()
Solution
Step 1: Identify the nullable object and property access
useris nullable, so accessinglengthdirectly without safe call is unsafe.Step 2: Correct safe call placement
The safe call operator must be used on the nullable object:user?.length. The codeuser.length?.toString()tries to accesslengthon a nullable object without safety, causing an error.Final Answer:
The safe call operator should be beforelength, likeuser?.length. -> Option AQuick Check:
Safe call must be on nullable object [OK]
- Using safe call after property instead of before
- Ignoring nullability of variable
- Misunderstanding function call on nullable
val items: List?, which expression safely gets the length of the first string or returns null if any part is null?Solution
Step 1: Understand the nullability
itemscan be null, and its elements can also be null. So both the list and the first element might be null.Step 2: Use safe calls to avoid errors
To safely get the length of the first string, useitems?.get(0)?.length. This returns null ifitemsor the first element is null.Final Answer:
items?.get(0)?.length -> Option AQuick Check:
Chain safe calls for nested nullables [OK]
- Using !! which throws exception if null
- Missing safe call on list or element
- Using invalid syntax like ?[0]
Ready to prove it?
Pass the test and this pattern moves unknown
