Mastering Kotlin Smart Casts with Contracts: Beyond the Basics
Bridge the gap between custom helper functions and the Kotlin compiler to write cleaner, safer, and more idiomatic code. Kotlin’s smart casting is a superpower. It allows the compiler to automatically infer types after a check, simplifying your code. But what happens when you abstract that logic into helper functions? Suddenly, the compiler loses its magic touch. Enter Kotlin Contracts : a way to bridge the gap between your custom logic and the compiler’s static analysis. The Smart Cast Dilemma Consider a standard sealed hierarchy for a messaging app: sealed interface Account class Moderator ( val badgeId: String) : Account class StandardUser ( val username: String) : Account When you perform an explicit check, Kotlin is happy: fun handleAccount (account: Account ) { if (account is Moderator) { println(account.badgeId) // ✅ Smart-cast works! } } But the moment you move that check into a reusable function, the magic breaks: fun isMod (account: Accou...