Kotlin Smart Cast Is Impossible Because Is a Mutable Property

Oct 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}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.