In Kotlin you can create a data class
:
data class CountriesResponse(
val count: Int,
val countries: List<Country>,
val error: String)
Then you can use it to parse a JSON, for instance, "{n: 10}". In this case you will have an object val countries: CountriesResponse
, received from Retrofit
, Fuel
or Gson
, that contains these values: count = 0, countries = null, error = null
.
In Kotlin + Gson - How to get an emptyList when null for data class you can see another example.
When you later try to use countries
, you will get an exception here: val size = countries.countries.size
: "kotlin.TypeCastException: null cannot be cast to non-null type kotlin.Int". If you write a code and use ?
when accessing these fields, Android Studio will highlight ?.
and warn: Unnecessary safe call on a non-null receiver of type List<Country>
.
So, should we use ?
in data classes? Why can an application set null
to non-nullable variables during runtime?