Skip to content
Latchkey

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 time

Common 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

  1. Replace the check-then-use with ?. or ?:.
  2. Make the property a val where ownership allows.
  3. Use let to 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →