0
0
Kotlinprogramming~5 mins

Type checking with is operator in Kotlin

Choose your learning style9 modes available
Introduction
We use the is operator to check if a value is of a certain type. It helps us decide what to do based on the kind of data we have.
When you want to do different things depending on the type of a variable.
When you receive input that could be different types and need to handle each type safely.
When you want to avoid errors by making sure a variable is the right type before using it.
When you want to write clear and safe code that adapts to different data types.
Syntax
Kotlin
if (variable is Type) {
    // code to run if variable is of Type
}
The is operator checks if the variable is an instance of the specified type.
Inside the if block, Kotlin smart casts the variable to that type automatically.
Examples
Checks if obj is a String, then prints its length.
Kotlin
val obj: Any = "Hello"
if (obj is String) {
    println(obj.length)  // obj is treated as String here
}
Checks if number is an Int, then adds 10 and prints.
Kotlin
val number: Any = 42
if (number is Int) {
    println(number + 10)  // number is Int here
}
Function that prints different messages based on whether x is a Double.
Kotlin
fun checkType(x: Any) {
    if (x is Double) {
        println("Double value: $x")
    } else {
        println("Not a Double")
    }
}
Sample Program
This program goes through a list of different types. It uses the is operator to check each item's type and prints a message accordingly.
Kotlin
fun main() {
    val items: List<Any> = listOf("apple", 5, 3.14, true)
    for (item in items) {
        when {
            item is String -> println("String of length ${item.length}")
            item is Int -> println("Integer value: $item")
            item is Double -> println("Double value: $item")
            else -> println("Unknown type")
        }
    }
}
OutputSuccess
Important Notes
The is operator works like 'instanceof' in other languages but with smart casting.
You can use !is to check if a variable is NOT a certain type.
Smart casting only works if the variable is immutable (val) or not changed between checks.
Summary
Use the is operator to check a variable's type safely.
Inside the if block, Kotlin treats the variable as that type automatically.
This helps write clear and error-free code when working with different data types.