Reputation: 9414
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 ?
Upvotes: 0
Views: 1534
Reputation: 89678
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
}
Upvotes: 3