Smart casts in when and if in Kotlin - Time & Space Complexity
We want to understand how the time needed to run code with smart casts in when and if changes as input grows.
How does checking types and branching affect the work done?
Analyze the time complexity of the following code snippet.
fun describe(obj: Any): String {
return when (obj) {
is String -> "String of length ${obj.length}"
is Int -> "Integer value $obj"
else -> "Unknown type"
}
}
fun checkAndPrint(list: List) {
for (item in list) {
if (item is String) {
println("String: ${item.length}")
} else {
println("Not a string")
}
}
}
This code uses smart casts inside when and if to check types and then access properties safely.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each item in the list in
checkAndPrint. - How many times: Once for each element in the input list.
Each item in the list is checked once to see if it is a String, then printed accordingly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and prints |
| 100 | About 100 type checks and prints |
| 1000 | About 1000 type checks and prints |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Smart casts make the code run faster than just checking types manually, so time complexity is less than linear."
[OK] Correct: Smart casts help with safe access but do not reduce the need to check each item once, so the time still grows with input size.
Understanding how type checks and smart casts affect performance shows you can reason about code efficiency and safety together, a useful skill in real projects.
What if we replaced the for loop with a recursive function? How would the time complexity change?