0
0
Kotlinprogramming~5 mins

Safe casts with as? in Kotlin

Choose your learning style9 modes available
Introduction

Safe casts let you try to change a value's type without causing errors if it doesn't fit. It helps keep your program running smoothly.

When you want to convert a value to a different type but aren't sure if it will work.
When reading data from a source that might have mixed types, like user input or JSON.
When working with objects that might be different subclasses and you want to safely check their type.
When you want to avoid your program crashing due to a wrong type cast.
Syntax
Kotlin
val result = value as? TargetType

The as? operator tries to cast value to TargetType.

If the cast works, result holds the new type; if not, result is null.

Examples
This tries to cast obj to a String. It works, so str holds "Hello".
Kotlin
val obj: Any = "Hello"
val str: String? = obj as? String
This tries to cast an Int to a String. It fails, so str is null.
Kotlin
val obj: Any = 123
val str: String? = obj as? String
Even if obj is null, the safe cast returns null without error.
Kotlin
val obj: Any? = null
val str: String? = obj as? String
Sample Program

This program tries to safely cast two values to String. The first cast works and prints the string. The second fails and prints null without crashing.

Kotlin
fun main() {
    val unknown: Any = "Kotlin"
    val safeCast: String? = unknown as? String
    println("Safe cast result: $safeCast")

    val number: Any = 42
    val failedCast: String? = number as? String
    println("Failed cast result: $failedCast")
}
OutputSuccess
Important Notes

Use safe casts when you want to avoid exceptions from wrong type conversions.

If you use the regular as operator and the cast fails, your program will crash with a ClassCastException.

Safe casts return null on failure, so check for null before using the result.

Summary

Safe casts with as? try to convert a value's type without crashing.

If the cast is not possible, they return null instead of throwing an error.

This helps keep your program safe and stable when working with uncertain types.