What if your program could instantly know what kind of data it's dealing with, avoiding costly mistakes?
Why Type checking with is operator in Kotlin? - Purpose & Use Cases
Imagine you have a box with different types of toys mixed inside. You want to find out which toys are cars and which are dolls by opening each one and guessing.
Manually checking each toy by guessing is slow and you might make mistakes. You could call a wrong method on a toy that doesn't support it, causing errors or crashes.
The is operator in Kotlin lets you quickly and safely check the type of an object before using it. This way, you only treat toys as cars if they really are cars, avoiding mistakes.
if (obj is Car) { (obj as Car).drive() }
if (obj is Car) {
obj.drive() // No cast needed
}It enables safe and clear code that adapts behavior based on the actual type of data at runtime.
In a game, you might have different characters like warriors and mages. Using is, you can check if a character is a mage before casting a magic spell.
Manually guessing types is error-prone and slow.
is operator checks types safely and clearly.
It helps write flexible code that works with different data types.
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
