Type checking is a fundamental concept in programming, and Kotlin makes it simple with is
and !is
. These operators help you check whether an object is of a certain type and allow you to write safe and concise code. In this post, we’ll break down how type checks (is
and !is
) in Kotlin work, with clear examples to help you understand their use cases.
What Are Type Checks in Kotlin?
In Kotlin, every variable has a type. Sometimes, you need to confirm whether a variable belongs to a particular type before performing operations on it. The is
operator checks if an object is of a specified type, while !is
checks if it is not.
So, Kotlin provides two primary operators for type checking:
is
– Checks if an object is of a particular type.!is
– Checks if an object is NOT of a particular type.
Let’s explore each of these in detail with examples.
How the is
Operator Works
The is
operator checks whether an object is of a specific type. If the object matches the type, it returns true
; otherwise, it returns false
.
fun checkType(value: Any) {
if (value is String) {
println("It's a string with length: ${value.length}")
} else {
println("Not a string")
}
}
fun main() {
checkType("Hello, Kotlin!") // Output: It's a string with length: 14
checkType(42) // Output: Not a string
}
Here,
value is String
checks ifvalue
is of typeString
.- If
value
is indeed aString
, Kotlin automatically casts it within theif
block. - This smart casting avoids explicit type conversion, making the code cleaner.
How the !is
Operator Works
The !is
operator is the opposite of is
. It checks whether an object is not of a certain type.
fun checkNotType(value: Any) {
if (value !is Int) {
println("Not an Integer")
} else {
println("It's an Integer with value: $value")
}
}
fun main() {
checkNotType(100) // Output: It's an Integer with value: 100
checkNotType("Kotlin") // Output: Not an Integer
}
value !is Int
returnstrue
ifvalue
is not anInt
.- If
value
is not anInt
, it prints “Not an Integer”. - Otherwise, it prints the integer value.
Type Checking with when
Expressions
Kotlin’s when
expression works well with type checks (is
and !is
). This is especially useful for handling multiple types in a concise manner.
fun identifyType(value: Any) {
when (value) {
is String -> println("It's a string of length ${value.length}")
is Int -> println("It's an integer: $value")
is Double -> println("It's a double: $value")
else -> println("Unknown type")
}
}
fun main() {
identifyType("Hello") // Output: It's a string of length 5
identifyType(10) // Output: It's an integer: 10
identifyType(5.5) // Output: It's a double: 5.5
identifyType(true) // Output: Unknown type
}
when
checks the type ofvalue
usingis
.- Depending on the type, it prints an appropriate message.
- The
else
block ensures unhandled types don’t cause errors.
Smart Casting and Type Safety
One of Kotlin’s biggest advantages is smart casting, which reduces the need for explicit type casting.
fun printLength(obj: Any) {
if (obj is String) {
// Smart cast: No need to explicitly cast obj to String
println("String length: ${obj.length}")
}
}
fun main() {
printLength("Kotlin") // Output: String length: 6
}
Why is this useful?
- No need for explicit casting (
obj as String
). - Improves readability and prevents unnecessary type conversion errors.
Common Mistakes and Best Practices
1. Forgetting the Smart Cast Scope
fun invalidCast(obj: Any) {
if (obj is String) {
// Smart cast works here
println(obj.length)
}
// println(obj.length) // Error: Smart cast is lost outside if block
}
Solution: Store the casted value in a variable if needed outside the block.
2. Using is
with Nullable Types
fun checkNullable(value: Any?) {
if (value is String) {
println(value.length) // Safe
}
}
is
works with nullable types, but the variable remains nullable outside theif
block.- Use the safe call operator (
?.
) to avoidNullPointerException
.
3. Also, use when
for Multiple Type Checks – This makes code cleaner and more readable.
Conclusion
Type checks (is
and !is
) in Kotlin are powerful tools for ensuring type safety and improving code clarity. The is
operator checks if a variable belongs to a specific type, while !is
ensures it doesn’t. These operators shine in if
conditions, when
expressions, and smart casting scenarios, making Kotlin a safer and more intuitive language.