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.
Safe casts with as? in 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.
obj to a String. It works, so str holds "Hello".val obj: Any = "Hello" val str: String? = obj as? String
Int to a String. It fails, so str is null.val obj: Any = 123 val str: String? = obj as? String
obj is null, the safe cast returns null without error.val obj: Any? = null val str: String? = obj as? String
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.
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") }
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.
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.