为什么 Kotlin 在声明为不可空字符串的属性中接受空值?

Why is Kotlin accepting a null value in an attribute declared as a non-nullable string?

我这样声明 data class

data class Product(val name: String = "", val price: Float = 0f)

我的代码是:

val json = "{'name': null, 'price': 50.00}"
val gson = GsonBuilder().create()
val p = gson.fromJson(json, Product::class.java)
println("name is ${p.name}")

控制台输出为:name is null

这怎么可能? 名称属性不是可为空的字符串。

这是将 Gson 与 Kotlin 结合使用时的常见问题 - 此处运行时错误发生得太晚,这可能会使您的程序不稳定且易于崩溃。例如,写:

val name: String = p.name

轰!崩溃。

Gson 简单地按照 super hacky implementation 为 class 分配内存而不调用构造函数,然后使用反射使用 JSON 中存在的值填充字段。

这使得在 Kotlin 的非空属性中存储 null 成为可能,这可能会在运行时导致 NPE。您可以提供自定义 TypeAdapter 来为您的 class.

禁用反射