How to Use is Keyword in Kotlin: Type Checking Made Easy
In Kotlin, the
is keyword checks if a variable is of a specific type and returns a Boolean. It is used like variable is Type to test the type at runtime, enabling safe type checks and smart casts.Syntax
The is keyword is used to check if a value is of a certain type. The syntax is:
variable is Type: Returnstrueifvariableis an instance ofType.variable !is Type: Returnstrueifvariableis NOT an instance ofType.
This helps you safely check types before using them.
kotlin
if (obj is String) { // obj is treated as String here } if (obj !is Int) { // obj is NOT an Int }
Example
This example shows how to use is to check a variable's type and then use it safely with smart casting.
kotlin
fun describe(obj: Any): String {
return if (obj is String) {
"String of length ${obj.length}"
} else if (obj is Int) {
"Integer value $obj"
} else {
"Unknown type"
}
}
fun main() {
println(describe("Hello"))
println(describe(42))
println(describe(3.14))
}Output
String of length 5
Integer value 42
Unknown type
Common Pitfalls
One common mistake is to check the type but then cast manually instead of relying on Kotlin's smart cast. Also, is only works with non-nullable types unless you handle null explicitly.
Wrong approach:
if (obj is String) {
val str = obj as String // unnecessary cast
println(str.length)
}Right approach:
if (obj is String) {
println(obj.length) // smart cast automatically treats obj as String
}Quick Reference
| Usage | Description |
|---|---|
| variable is Type | Returns true if variable is an instance of Type |
| variable !is Type | Returns true if variable is NOT an instance of Type |
| Smart cast after is check | Variable is automatically cast to Type inside the if block |
| Works with nullable types | Use with care; null is not an instance of any type |
Key Takeaways
Use
is to check a variable's type safely at runtime.Kotlin smart casts the variable inside the
if (variable is Type) block automatically.Avoid unnecessary manual casts after using
is.!is checks if a variable is NOT of a certain type.Remember that
is does not consider null as an instance of any type.