Quick Answer
Compiler tracks type checks and auto-casts
Understanding the Issue
After performing an is-check, Kotlin automatically casts the variable to that type within the scope of the check, eliminating the need for explicit casting.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Explicit casting
if (obj is String) {
val length = (obj as String).length // Redundant cast
}
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution: Smart cast
if (obj is String) {
val length = obj.length // Automatically cast to String
}
Key Takeaways
Let the compiler handle safe casting after type checks.