Kotlin "Smart cast is impossible" in CI
The compiler cannot smart-cast a value after a null or type check because the value could change between the check and the use. Mutable, open, or custom-getter properties block smart casts.
What this error means
The build fails with Smart cast to X is impossible, because Y is a mutable property that could have been changed by this time. It is deterministic.
gradle
e: file:///src/main/kotlin/App.kt:9:13 Smart cast to 'String' is
impossible, because 'config.name' is a mutable property that could
have been changed by this timeCommon causes
Mutable property checked then used
A var (or a property with a custom getter) could change between the null check and the use, so the compiler refuses to assume the checked type.
Open or interface property
A property from another module or an open class could be overridden with a custom getter, defeating smart casts.
How to fix it
Bind to a local val
Capture the value in a local immutable variable, then check and use that.
App.kt
val name = config.name
if (name != null) println(name.length)Use a safe call or elvis
- Replace the check-then-use with
?.or?:. - Make the property a val where ownership allows.
- Use
letto scope the non-null value.
App.kt
config.name?.let { println(it.length) }How to prevent it
- Prefer val over var for checked values.
- Capture mutable properties in locals before use.
- Use safe calls and let for nullable access.
Related guides
Kotlin "Type mismatch" in CIFix the Kotlin "Type mismatch: inferred type is X but Y was expected" compile error in Gradle CI builds - inc…
Kotlin "incompatible types" in when expression in CIFix the Kotlin "incompatible types" / non-exhaustive when error in Gradle CI when a when expression branches…
Kotlin "None of the following functions can be called" in CIFix the Kotlin "None of the following functions can be called with the arguments supplied" overload-resolutio…