How to Use Safe Cast in Kotlin: Simple Guide
In Kotlin, use the
as? operator for safe casting, which tries to cast an object to a type and returns null if it fails instead of throwing an exception. This helps avoid crashes by safely handling incompatible types.Syntax
The safe cast operator in Kotlin is as?. It attempts to cast a value to a specified type and returns null if the cast is not possible.
value as? Type: Tries to castvaluetoType.- If
valueis not ofType, it returnsnullinstead of throwing an exception.
kotlin
val obj: Any = "Hello" val str: String? = obj as? String val num: Int? = obj as? Int
Example
This example shows how to safely cast an Any type to String and Int using as?. It prints the cast result or a message if the cast fails.
kotlin
fun main() {
val obj: Any = "Kotlin"
val safeString: String? = obj as? String
println("Safe cast to String: $safeString")
val safeInt: Int? = obj as? Int
if (safeInt == null) {
println("Safe cast to Int failed, returned null")
} else {
println("Safe cast to Int: $safeInt")
}
}Output
Safe cast to String: Kotlin
Safe cast to Int failed, returned null
Common Pitfalls
Using the regular cast operator as instead of as? can cause your program to crash with a ClassCastException if the cast is invalid. Always use as? when you are not sure about the type to avoid exceptions.
Also, remember that as? returns null on failure, so handle the null case to prevent NullPointerException.
kotlin
fun main() {
val obj: Any = "Hello"
// Unsafe cast - throws exception if fails
// val unsafeInt: Int = obj as Int // This will crash
// Safe cast - returns null if fails
val safeInt: Int? = obj as? Int
println(safeInt) // Prints: null
}Output
null
Quick Reference
| Operator | Description | Returns on Failure |
|---|---|---|
| as | Unsafe cast, throws exception if cast fails | Throws ClassCastException |
| as? | Safe cast, returns null if cast fails | null |
Key Takeaways
Use
as? for safe casting to avoid exceptions on invalid casts.Safe cast returns
null if the object is not of the target type.Always check for
null after a safe cast to prevent null pointer errors.Avoid using
as unless you are sure the cast will succeed.Safe cast helps write more robust and crash-free Kotlin code.