What if your program could try a risky action without crashing, just like testing a fruit before biting?
Why Safe casts with as? in Kotlin? - Purpose & Use Cases
Imagine you have a box labeled 'Fruit' but inside it could be an apple or a banana. You want to take out the apple and eat it, but if it's not an apple, you might get hurt trying to bite it.
Manually checking the type of an object before using it is slow and messy. You might forget to check, causing your program to crash unexpectedly. It's like blindly biting into the box hoping it's an apple.
Safe casts with as? let you try to convert an object to a type safely. If it's the right type, you get the object; if not, you get null instead of a crash. It's like gently checking if the fruit is an apple before biting.
if (obj is String) { val str = obj // use str } else { // handle not a String }
val str: String? = obj as? String if (str != null) { // use str safely }
This lets your program handle uncertain types gracefully, avoiding crashes and making your code cleaner and safer.
When reading data from a mixed list of objects, you can safely try to treat each item as a specific type without worrying about errors stopping your app.
Manual type checks are error-prone and clutter code.
as? safely tries to cast and returns null if it fails.
It helps write safer, cleaner, and more reliable Kotlin code.