在Kotlin你可以创建一个data class:
data class CountriesResponse(
val count: Int,
val countries: List<Country>,
val error: String)
Run Code Online (Sandbox Code Playgroud)
然后您可以使用它来解析JSON,例如"{n:10}".在这种情况下,你将有一个对象val countries: CountriesResponse,从收到的Retrofit,Fuel或Gson包含这些值:count = 0, countries = null, error = null.
在Kotlin + Gson中 - 如何在数据类为null时获取emptyList,您可以看到另一个示例.
当您稍后尝试使用时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在运行时设置为不可为空的变量?