0
0
KotlinHow-ToBeginner · 3 min read

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 cast value to Type.
  • If value is not of Type, it returns null instead 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

OperatorDescriptionReturns on Failure
asUnsafe cast, throws exception if cast failsThrows ClassCastException
as?Safe cast, returns null if cast failsnull

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.