Nullable types with ? suffix in Kotlin - Time & Space Complexity
We want to understand how using nullable types with the ? suffix affects the time it takes for a program to run.
Specifically, does checking for null add extra work as the input grows?
Analyze the time complexity of the following code snippet.
fun printLengths(strings: List) {
for (str in strings) {
if (str != null) {
println(str.length)
} else {
println("Null string")
}
}
}
This code goes through a list of strings that can be null and prints their length or a message if null.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once per item in the list.
As the list gets bigger, the program checks each item once, whether it is null or not.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and prints |
| 100 | About 100 checks and prints |
| 1000 | About 1000 checks and prints |
Pattern observation: The work grows directly with the number of items. More items mean more checks and prints.
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: "Checking for null makes the program slower in a way that depends on how many nulls there are."
[OK] Correct: The program always checks each item once, no matter if it is null or not. The number of nulls does not change how many times it checks.
Understanding how nullable types affect performance helps you write clear and efficient Kotlin code, a useful skill in many coding situations.
What if we replaced the list with a nested list of nullable strings? How would the time complexity change?
Practice
? after a type in Kotlin mean?Solution
Step 1: Understand Kotlin type suffix
In Kotlin, adding?after a type means the variable can hold null.Step 2: Compare with non-nullable types
Without?, variables cannot be null and will cause errors if assigned null.Final Answer:
The variable can hold a null value. -> Option BQuick Check:
Nullable type = variable can be null [OK]
? means nullable type in Kotlin [OK]- Thinking
?makes variable immutable - Confusing
?with constant declaration - Assuming
?means function type
Solution
Step 1: Recall Kotlin nullable syntax
Kotlin uses?after the type name to mark it nullable, e.g.,String?.Step 2: Check each option
var name: String? usesString?correctly. Options A, B, and D use invalid syntax.Final Answer:
var name: String? -> Option AQuick Check:
Nullable syntax = type followed by?[OK]
? right after the type name for nullable [OK]- Placing
?before the type - Using
!instead of? - Writing 'nullable' keyword explicitly
var text: String? = null println(text?.length ?: "No length")
Solution
Step 1: Understand safe call and Elvis operator
text?.lengthsafely accesses length if text is not null; else returns null. The Elvis operator?:provides "No length" if left side is null.Step 2: Evaluate given code
Sincetextis null,text?.lengthis null, so the expression prints "No length".Final Answer:
No length -> Option CQuick Check:
Safe call + Elvis = fallback value [OK]
- Expecting NullPointerException on null safe call
- Thinking null?.length returns 0
- Ignoring Elvis operator fallback
var number: Int? = 10 var result: Int = number + 5
Solution
Step 1: Check type compatibility
numberis nullableInt?, butresultexpects non-nullInt. Adding nullable and non-null directly is not allowed.Step 2: Understand Kotlin's null safety
You must safely unwrapnumberbefore adding, e.g., usingnumber ?: 0or safe call.Final Answer:
Cannot add Int? and Int directly. -> Option DQuick Check:
Nullable + non-null Int needs safe unwrap [OK]
- Assuming nullable Int can be used like Int
- Ignoring need for safe call or Elvis operator
- Thinking semicolon is required in Kotlin
val items: List?. How do you safely print the length of the first item or print 0 if the list or first item is null?Solution
Step 1: Analyze nullable types
itemscan be null, and its elements can be null. So both list and first item need safe calls.Step 2: Use safe calls and Elvis operator
items?.get(0)?.length ?: 0safely accesses first item length or returns 0 if null.Final Answer:
println(items?.get(0)?.length ?: 0) -> Option AQuick Check:
Safe calls chain + fallback = safe nullable access [OK]
- Using !! which throws exception if null
- Missing safe call on first item
- Assuming list or item can't be null
Ready to prove it?
Pass the test and this pattern moves unknown
