0

I have some classes and I have converted them from Java to Kotlin.

This is the Kotlin method:

private var allCountriesList: List<Country>? = null

        val allCountries: List<Country>
            get() {

                val locales = Locale.getISOCountries()
                val countries = ArrayList<Country>()

                for (countryCode in locales) {

                    val obj = Locale("", countryCode)
                    Log.i("AMIRA2020", obj.country + " / " + obj.displayName)
                    if (obj.country == "SP" == false && obj.country == "ZG" == false)
                        countries.add(Country(obj.country, obj.displayName, -1))
                }

                Collections.sort(countries) { o1, o2 -> o1.name!!.compareTo(o2.name!!) }

                allCountriesList = countries

                return allCountriesList
            }

I am getting an error in the return statement that the smart case is impossible.

Can anyone help please ?

Onik
  • 19,396
  • 14
  • 68
  • 91
Amira Elsayed Ismail
  • 9,216
  • 30
  • 92
  • 175
  • Possible duplicate of [Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time](https://stackoverflow.com/questions/44595529/smart-cast-to-type-is-impossible-because-variable-is-a-mutable-property-tha) – Zoe Jun 19 '19 at 15:03

1 Answers1

3

The issue is that allCountriesList is a nullable property, and allCountries has to return a non-null value. You might expect that setting allCountriesList to a non-null List before returning it makes this safe, but it doesn't.

For example, between these two lines, another thread could get CPU time, and set allCountriesList back to null, which you can't return from the getter of allCountries.

allCountriesList = countries
return allCountriesList

So the solution is to return the list you know to be non-null within this scope (and not accessible from other threads), countries:

val allCountries: List<Country>
    get() {

        ...
        val countries = ArrayList<Country>()
        ...

        allCountriesList = countries

        return countries
    }
zsmb13
  • 85,752
  • 11
  • 221
  • 226