0
0
Kotlinprogramming~5 mins

Safe casts with as? in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Safe casts with as?
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Safe cast check obj as? String inside the loop.
  • How many times: Once per item in the list, so as many times as the list size.
How Execution Grows With Input

Each item requires one safe cast check. So if the list doubles in size, the total checks double too.

Input Size (n)Approx. Operations
1010 safe cast checks
100100 safe cast checks
10001000 safe cast checks

Pattern observation: The number of operations grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to safely cast all items grows linearly with the number of items.

Common Mistake

[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.

Interview Connect

Understanding how safe casts scale helps you reason about type checks in real apps, showing you can think about performance even in simple operations.

Self-Check

"What if we replaced the list with a nested list and tried safe casting on inner elements? How would the time complexity change?"