Type checking with is operator in Kotlin - Time & Space Complexity
We want to understand how long it takes to check an object's type using the is operator in Kotlin.
How does the time needed change as we check more objects?
Analyze the time complexity of the following code snippet.
fun countStrings(items: List<Any>): Int {
var count = 0
for (item in items) {
if (item is String) {
count++
}
}
return count
}
This code counts how many items in a list are strings by checking each item's type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list and checking its type with
is. - How many times: Once for every item in the list.
As the list gets bigger, the number of type checks grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The work doubles when the list size doubles, growing in a straight line.
Time Complexity: O(n)
This means the time to check types grows directly with the number of items in the list.
[X] Wrong: "Type checking with is is instant and does not depend on list size."
[OK] Correct: Each item must be checked one by one, so more items mean more checks and more time.
Understanding how type checks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we checked types only for the first half of the list? How would the time complexity change?"
Practice
is operator do in Kotlin?Solution
Step 1: Understand the purpose of
Theisoperatorisoperator is used to check if a variable holds a value of a certain type.Step 2: Differentiate from other options
It does not change, create, or delete variables; it only checks type.Final Answer:
Checks if a variable is of a specific type -> Option AQuick Check:
Type check = A [OK]
is means 'is this type?' check [OK]- Thinking
ischanges the variable type - Confusing
iswith variable creation - Assuming
isdeletes variables
obj is a String in Kotlin?Solution
Step 1: Recall Kotlin syntax for type checking
Kotlin usesiskeyword to check types, notinstanceofor other keywords.Step 2: Match the correct syntax
The correct syntax isif (obj is String).Final Answer:
if (obj is String) -> Option BQuick Check:
Correct syntax = C [OK]
is keyword, not Java's instanceof [OK]- Using Java syntax
instanceofin Kotlin - Writing
obj type Stringwhich is invalid - Comparing with
==instead of type check
fun checkType(x: Any) {
if (x is Int) {
println(x + 5)
} else {
println("Not an Int")
}
}
checkType(10)
checkType("Hello")Solution
Step 1: Analyze the first call
10 is an Int, so inside the if block,checkType(10)x + 5equals 15, printed as "15".Step 2: Analyze the second call
"Hello" is not an Int, so else block runs printing "Not an Int".checkType("Hello")Final Answer:
15 Not an Int -> Option DQuick Check:
Int check prints sum, else prints message = A [OK]
is true, use variable as that type inside block [OK]- Assuming string "Hello" can be added to 5
- Expecting runtime error instead of else output
- Confusing output order
fun printLength(obj: Any) {
if (obj is String) {
println(obj.length())
}
}Solution
Step 1: Check usage of
In Kotlin,lengthon Stringlengthis a property, not a function, so it should not have parentheses.Step 2: Confirm other parts are correct
Theisoperator is used correctly and else block is optional.Final Answer:
Using parentheses withlengthproperty -> Option CQuick Check:
Property access no parentheses = D [OK]
- Adding parentheses to properties like
length - Thinking else block is mandatory
- Misusing
isoperator syntax
Any elements, how can you create a new list containing only the strings using the is operator in Kotlin?Solution
Step 1: Understand filtering by type
To get only strings, Kotlin providesfilterIsInstance<String>()which filters elements by type safely.Step 2: Evaluate other options
val strings = list.filter { it is String } filters byis Stringbut keeps type asAny, not cast to String. val strings = list.map { if (it is String) it else null } maps to nullable list, not filtering. val strings = list.filter { it == String } compares with type itself, which is invalid.Final Answer:
val strings = list.filterIsInstance<String>() -> Option AQuick Check:
UsefilterIsInstancefor type filtering [OK]
filterIsInstance to get typed list quickly [OK]- Using
filterwithout casting - Mapping to nullable instead of filtering
- Comparing element to type object
Ready to prove it?
Pass the test and this pattern moves unknown
