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.
if (variable is Type) { // code to run if variable is of Type }
val obj: Any = "Hello" if (obj is String) { println(obj.length) // obj is treated as String here }
val number: Any = 42 if (number is Int) { println(number + 10) // number is Int here }
fun checkType(x: Any) { if (x is Double) { println("Double value: $x") } else { println("Not a Double") } }
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") } } }
is operator do in Kotlin?is operatoris operator is used to check if a variable holds a value of a certain type.is means 'is this type?' check [OK]is changes the variable typeis with variable creationis deletes variablesobj is a String in Kotlin?is keyword to check types, not instanceof or other keywords.if (obj is String).is keyword, not Java's instanceof [OK]instanceof in Kotlinobj type String which is invalid== instead of type checkfun checkType(x: Any) {
if (x is Int) {
println(x + 5)
} else {
println("Not an Int")
}
}
checkType(10)
checkType("Hello")checkType(10)x + 5 equals 15, printed as "15".checkType("Hello")is true, use variable as that type inside block [OK]fun printLength(obj: Any) {
if (obj is String) {
println(obj.length())
}
}length on Stringlength is a property, not a function, so it should not have parentheses.is operator is used correctly and else block is optional.length property -> Option Clengthis operator syntaxAny elements, how can you create a new list containing only the strings using the is operator in Kotlin?filterIsInstance<String>() which filters elements by type safely.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.filterIsInstance for type filtering [OK]filterIsInstance to get typed list quickly [OK]filter without castingPass the test and this pattern moves unknown