0
0
Kotlinprogramming~5 mins

Smart casts in when and if in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Smart casts in when and if
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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.
How Execution Grows With Input

Each item in the list is checked once to see if it is a String, then printed accordingly.

Input Size (n)Approx. Operations
10About 10 type checks and prints
100About 100 type checks and prints
1000About 1000 type checks and prints

Pattern observation: The work grows directly with the number of items; doubling items doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items checked.

Common Mistake

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

Interview Connect

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.

Self-Check

What if we replaced the for loop with a recursive function? How would the time complexity change?