What if your program could remember what type something is, so you never have to convert it twice?
Why Smart casts in when and if in Kotlin? - Purpose & Use Cases
Imagine you have a box that might contain different types of items, like a toy or a book. To use the item properly, you need to check its type first and then tell the program exactly what it is before you can play or read it.
Manually checking the type and then converting it every time is slow and tiring. You might forget to convert it, causing errors, or write the same checks again and again, making your code messy and hard to fix.
Smart casts in when and if let the program automatically understand the type after you check it once. This means you can use the item directly without extra steps, making your code cleaner and safer.
if (obj is String) { val str = obj as String println(str.length) }
if (obj is String) {
println(obj.length)
}It lets you write simpler and safer code by trusting the program to remember type checks and avoid unnecessary conversions.
When reading user input that could be a number or text, smart casts help you handle each case easily without extra code to convert types again and again.
Manual type checks require extra conversions that slow you down.
Smart casts automatically remember type checks in when and if.
This makes your code cleaner, safer, and easier to read.