0
0
Kotlinprogramming~3 mins

Why Smart casts in when and if in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could remember what type something is, so you never have to convert it twice?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
if (obj is String) {
    val str = obj as String
    println(str.length)
}
After
if (obj is String) {
    println(obj.length)
}
What It Enables

It lets you write simpler and safer code by trusting the program to remember type checks and avoid unnecessary conversions.

Real Life Example

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.

Key Takeaways

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.