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?"
Practice
What does the safe cast operator as? do in Kotlin?
Solution
Step 1: Understand the safe cast operator
Theas?operator attempts to cast a value to a specified type safely.Step 2: Behavior on failure
If the cast is not possible, instead of throwing an error, it returnsnull.Final Answer:
It tries to cast a value to a type and returns null if it fails. -> Option CQuick Check:
Safe cast = returns null on failure [OK]
- Confusing safe cast with forced cast
- Thinking it throws an exception on failure
- Assuming it converts to string automatically
Which of the following is the correct syntax for a safe cast in Kotlin?
val x = obj ___ String
Solution
Step 1: Identify safe cast syntax
In Kotlin, the safe cast operator isas?which tries to cast safely.Step 2: Match syntax to code
The codeval x = obj as? Stringattempts to castobjtoStringsafely.Final Answer:
as? -> Option AQuick Check:
Safe cast syntax = as? [OK]
- Using as without question mark causes exception
- Confusing is (type check) with as? (cast)
- Using to which is for conversions, not casting
What will be the output of this Kotlin code?
val obj: Any = 123 val str: String? = obj as? String println(str)
Solution
Step 1: Analyze the cast attempt
Variableobjholds an integer123, but we try to cast it toStringusing safe castas?.Step 2: Safe cast behavior
Sinceobjis not aString, the safe cast returnsnullinstead of throwing an error.Final Answer:
null -> Option AQuick Check:
Safe cast fails = null output [OK]
- Expecting ClassCastException instead of null
- Thinking it converts integer to string automatically
- Confusing safe cast with forced cast
Identify the error in this Kotlin code snippet and fix it:
val obj: Any = "Hello" val num: Int = obj as? Int println(num)
Solution
Step 1: Analyze variable types and cast
The safe castobj as? Intreturnsnullif cast fails, so the result is nullableInt?.Step 2: Fix type mismatch
Declaringnumas non-nullableIntcauses a type mismatch error. Changing it toInt?fixes this.Final Answer:
Change val num: Int to val num: Int? -> Option BQuick Check:
Safe cast returns nullable type [OK]
- Using non-nullable type for safe cast result
- Replacing safe cast with forced cast causing exceptions
- Ignoring type mismatch errors
You have a list of Any objects: listOf(1, "two", 3.0, "four"). You want to create a new list containing only the strings using safe casts. Which Kotlin code correctly does this?
Solution
Step 1: Understand the goal
We want to safely cast each element toStringand keep only successful casts.Step 2: Analyze options
val strings = list.map { it as? String }.filterNotNull() uses safe castas?which returnsnullfor non-strings, then filters outnullvalues withfilterNotNull(). This correctly produces a list of strings.Step 3: Why others are incorrect
val strings = list.map { it as String } forces cast and will throw exception on non-strings. val strings = list.filter { it is String } filters by type but does not cast, so type is stillAny. val strings = list.mapNotNull { it as String? } tries to cast with forced cast insidemapNotNullwhich will throw exception.Final Answer:
val strings = list.map { it as? String }.filterNotNull() -> Option DQuick Check:
Safe cast + filterNotNull = filtered strings [OK]
- Using forced cast causing exceptions
- Filtering type without casting
- Misusing mapNotNull with forced cast
Ready to prove it?
Pass the test and this pattern moves unknown
