Kotlin Smart Cast Is Impossible Because Is a Mutable Property

October 21, 2018
Smart cast to ‘CLASS!’ is impossible, because ‘VARIABLE’ is a mutable property that could have been changed by this time

This usually happens when you check for null for class variable.

Solution: copy class variable to local variable.

class PinActivity : AppCompatActivity() {
    private var mapFragment: SupportMapFragment? = null

    fun loadMap() {
        // Smart cast to 'SupportMapFragment!' is impossible, because 'mapFragment' is a mutable property that could have been changed by this time
        /*
        if (mapFragment == null) {

        }
         */

        // copy class variable to local variable
        var localMapFragment = this.mapFragment
        if (localMapFragment == null) {
            localMapFragment = SupportMapFragment.newInstance()
            ...
        }
        else {
            ...
        }

        ...

        this.mapFragment = localMaFragment
    }
}

Or use safe calls.

mapFragment?.also {
  // do something
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.