Kotlin “Smart cast is impossible, because the property could have been changed by this time”

The IDE should give you a warning, explaining that after the null check, it’s possible that adapter.nameList was changed by another thread, and that when you call list.addAll(adapter.nameList), adapter.nameList could actually be null by that point (again, because a different thread could have changed the value. This would be a race condition).

You have a few solutions:

  1. Make nameList a val, which makes its reference final. Since it’s final, it’s guaranteed another thread can’t change it. This probably doesn’t fit your use case.

    class Adapter {
        val nameList : ArrayList<String>? = null
    }
    
  2. Create a local copy of name list before you do the check. Because it’s a local copy, the compiler knows that another thread can’t access it, and thus it can’t be changed. The local copy could be defined with either a var or a val in this case, but I recommend val.

    val nameList = adapter.nameList
    if (nameList != null) {
        list.addAll(nameList)
    }
    
  3. Use one of the utility functions that Kotlin provides for just such a case as this. The let function copies the reference it’s called on as a parameter using an inline function. This means that it effectively compiles down to be the same as #2, but it’s a bit more terse. I prefer this solution.

    adapter.nameList?.let { list.addAll(it) }
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)