Safe casts with as? in Kotlin - Time & Space Complexity
We want to understand how long it takes to perform safe casts using as? in Kotlin.
Specifically, how does the time grow when casting different objects?
Analyze the time complexity of the following code snippet.
fun safeCastExample(obj: Any): String? {
return obj as? String
}
fun main() {
val items = listOf(1, "hello", 3.14, "world")
for (item in items) {
println(safeCastExample(item))
}
}
This code tries to safely cast each item in a list to a String using as?.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Safe cast check
obj as? Stringinside the loop. - How many times: Once per item in the list, so as many times as the list size.
Each item requires one safe cast check. So if the list doubles in size, the total checks double too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 safe cast checks |
| 100 | 100 safe cast checks |
| 1000 | 1000 safe cast checks |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to safely cast all items grows linearly with the number of items.
[X] Wrong: "Safe casts are instant and do not depend on input size."
[OK] Correct: Each safe cast must check the type of the object, so more items mean more checks and more time.
Understanding how safe casts scale helps you reason about type checks in real apps, showing you can think about performance even in simple operations.
"What if we replaced the list with a nested list and tried safe casting on inner elements? How would the time complexity change?"