Kotlin compiler cannot guarantee a mutable property var has not been modified between type check and usage.
Kotlin's compiler performs smart casting (automatically casting an object after checking its type with 'is' or null-safety checks). However, if the property is a mutable variable ('var') belonging to a class, another thread or subclass getter could change its value between the check and its usage. The compiler flags this as an error because type safety cannot be guaranteed.
Performing type checks or null checks directly on a mutable member property ('var') instead of a local copy.
1class UserProfile {2 var email: String? = "admin@example.com"3}4 5fun sendEmail(profile: UserProfile) {6 if (profile.email != null) {7 // Error: Smart cast to 'String' is impossible, because 'profile.email' is a mutable property8 println("Email length: ${profile.email.length}") 9 }10}1class UserProfile {2 var email: String? = "admin@example.com"3}4 5fun sendEmail(profile: UserProfile) {6 // Fix 1: Store in a local immutable variable (val) which cannot be modified7 val currentEmail = profile.email8 if (currentEmail != null) {9 println("Email length: ${currentEmail.length}") // Smart cast allowed!10 }11 12 // Fix 2: Use safe call let block13 profile.email?.let { emailVal ->14 println("Email length: ${emailVal.length}") // Safe!15 }16}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Since profile.email is a var, it could theoretically be set to null by another thread immediately after the check if (profile.email != null), leading to a potential NullPointerException.