【发布时间】:2019-03-21 02:48:19
【问题描述】:
在 Kotlin 中,您可以创建 data class:
data class CountriesResponse(
val count: Int,
val countries: List<Country>,
val error: String)
然后您可以使用它来解析 JSON,例如“{n: 10}”。在这种情况下,您将有一个对象val countries: CountriesResponse,从Retrofit、Fuel 或Gson 接收,其中包含以下值:count = 0, countries = null, error = null。
在Kotlin + Gson - How to get an emptyList when null for data class 你可以看到另一个例子。
当您稍后尝试使用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>。
那么,我们应该在数据类中使用? 吗?为什么应用程序可以在运行时将null 设置为不可为空的变量?
【问题讨论】:
标签: android kotlin nullpointerexception gson