In Kotlin you can create a data class
:
data class CountriesResponse(
val count: Int,
val countries: List<Country>,
val error: String)
然后可以使用它来解析JSON,例如,"{n:10}".在本例中,您将有一个从Retrofit
、Fuel
或Gson
接收的对象val countries: CountriesResponse
,其中包含以下值:count = 0, countries = null, error = null
.
In Kotlin + Gson - How to get an emptyList when null for data class you can see another example.
当您稍后try 使用countries
时,您将在这里得到一个异常:val size = countries.countries.size
:"kotlin.TypeCastException:null不能转换为非null类型kotlin.Int".如果您编写代码并在访问这些字段时使用?
,Android Studio将突出显示?.
并警告: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?