Bird
Raised Fist0
Kotlinprogramming~10 mins

Type checking with is operator in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type checking with is operator
Start with variable
↓
Check: variable is Type?
No→Else branch or skip
Yes↓
Execute code for that type
↓
Continue or end
The program checks if a variable is a certain type using 'is'. If yes, it runs code for that type; if no, it skips or runs else.
Execution Sample
Kotlin
fun checkType(x: Any?) {
    if (x is String) {
        println("String of length ${x.length}")
    } else {
        println("Not a String")
    }
}
This function checks if x is a String and prints its length; otherwise, it prints 'Not a String'.
Execution Table
StepVariable xCondition (x is String)Branch TakenOutput
1Hellotrueif branchString of length 5
2123falseelse branchNot a String
3truefalseelse branchNot a String
4Kotlintrueif branchString of length 6
5—falseelse branchNot a String
💡 All inputs checked; function ends after printing output.
Variable Tracker
Variable xStartAfter 1After 2After 3After 4After 5
xHelloHello123trueKotlin—
Key Moments - 2 Insights
Why does the code inside 'if (x is String)' run only for some inputs?
Because the 'is' operator checks the actual type of x at runtime. Only when x is a String (rows 1 and 4) does the if branch run, as shown in the execution_table.
What happens if x is null? Does 'x is String' return true?
No, 'x is String' returns false if x is null, so the else branch runs (row 5). This is because null is not considered a String.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when x = 123?
ANot a String
BString of length 3
CError
DNo output
💡 Hint
Check row 2 in execution_table where x is 123 and condition is false.
At which step does the condition 'x is String' become true?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look at the Condition column in execution_table for true values.
If x was changed to an Int value 10, what would be the output?
AString of length 2
BError
CNot a String
DNo output
💡 Hint
Refer to how non-String types like true or 123 produce 'Not a String' in execution_table.
Concept Snapshot
Type checking with 'is' operator in Kotlin:
- Syntax: if (variable is Type) { ... }
- Checks if variable is of given Type at runtime
- Runs code inside if only if true
- Else branch runs if false
- Null is not considered any type
Full Transcript
This visual trace shows how Kotlin's 'is' operator checks a variable's type at runtime. The function checkType takes any value x. It tests if x is a String. If yes, it prints the string length. If no, it prints 'Not a String'. The execution table shows different inputs: 'Hello' and 'Kotlin' are Strings, so the if branch runs and prints length. Inputs like 123, true, and null are not Strings, so else branch runs. The variable tracker shows how x changes each step. Key moments clarify why only Strings pass the check and that null is not a String. The quiz tests understanding of outputs and condition results. This helps beginners see how type checking controls program flow in Kotlin.

Practice

(1/5)
1. What does the is operator do in Kotlin?
easy
A. Checks if a variable is of a specific type
B. Changes the type of a variable
C. Creates a new variable
D. Deletes a variable

Solution

  1. Step 1: Understand the purpose of is operator

    The is operator is used to check if a variable holds a value of a certain type.
  2. Step 2: Differentiate from other options

    It does not change, create, or delete variables; it only checks type.
  3. Final Answer:

    Checks if a variable is of a specific type -> Option A
  4. Quick Check:

    Type check = A [OK]
Hint: Remember: is means 'is this type?' check [OK]
Common Mistakes:
  • Thinking is changes the variable type
  • Confusing is with variable creation
  • Assuming is deletes variables
2. Which of the following is the correct syntax to check if obj is a String in Kotlin?
easy
A. if (obj instanceof String)
B. if (obj is String)
C. if (obj type String)
D. if (obj == String)

Solution

  1. Step 1: Recall Kotlin syntax for type checking

    Kotlin uses is keyword to check types, not instanceof or other keywords.
  2. Step 2: Match the correct syntax

    The correct syntax is if (obj is String).
  3. Final Answer:

    if (obj is String) -> Option B
  4. Quick Check:

    Correct syntax = C [OK]
Hint: Use is keyword, not Java's instanceof [OK]
Common Mistakes:
  • Using Java syntax instanceof in Kotlin
  • Writing obj type String which is invalid
  • Comparing with == instead of type check
3. What will be the output of this Kotlin code?
fun checkType(x: Any) {
    if (x is Int) {
        println(x + 5)
    } else {
        println("Not an Int")
    }
}

checkType(10)
checkType("Hello")
medium
A. Error at runtime
B. 10 Not an Int
C. 15 Hello5
D. 15 Not an Int

Solution

  1. Step 1: Analyze the first call checkType(10)

    10 is an Int, so inside the if block, x + 5 equals 15, printed as "15".
  2. Step 2: Analyze the second call checkType("Hello")

    "Hello" is not an Int, so else block runs printing "Not an Int".
  3. Final Answer:

    15 Not an Int -> Option D
  4. Quick Check:

    Int check prints sum, else prints message = A [OK]
Hint: If is true, use variable as that type inside block [OK]
Common Mistakes:
  • Assuming string "Hello" can be added to 5
  • Expecting runtime error instead of else output
  • Confusing output order
4. Identify the error in this Kotlin code snippet:
fun printLength(obj: Any) {
    if (obj is String) {
        println(obj.length())
    }
}
medium
A. No error, code is correct
B. Missing else block after if
C. Using parentheses with length property
D. Incorrect use of is operator

Solution

  1. Step 1: Check usage of length on String

    In Kotlin, length is a property, not a function, so it should not have parentheses.
  2. Step 2: Confirm other parts are correct

    The is operator is used correctly and else block is optional.
  3. Final Answer:

    Using parentheses with length property -> Option C
  4. Quick Check:

    Property access no parentheses = D [OK]
Hint: Remember: Kotlin properties have no parentheses [OK]
Common Mistakes:
  • Adding parentheses to properties like length
  • Thinking else block is mandatory
  • Misusing is operator syntax
5. Given a list of Any elements, how can you create a new list containing only the strings using the is operator in Kotlin?
hard
A. val strings = list.filterIsInstance<String>()
B. val strings = list.filter { it is String }
C. val strings = list.map { if (it is String) it else null }
D. val strings = list.filter { it == String }

Solution

  1. Step 1: Understand filtering by type

    To get only strings, Kotlin provides filterIsInstance<String>() which filters elements by type safely.
  2. Step 2: Evaluate other options

    val strings = list.filter { it is String } filters by is String but keeps type as Any, 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.
  3. Final Answer:

    val strings = list.filterIsInstance<String>() -> Option A
  4. Quick Check:

    Use filterIsInstance for type filtering [OK]
Hint: Use filterIsInstance to get typed list quickly [OK]
Common Mistakes:
  • Using filter without casting
  • Mapping to nullable instead of filtering
  • Comparing element to type object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard