简体   繁体   English

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

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

I declared a data class like this:我声明了一个这样的data class

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

My code is:我的代码是:

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

The console output is: name is null控制台输出为: name is null

How is this possible?这怎么可能? The name attribute is not a nullable string. name 属性不是可为空的字符串。

That's common problem when using Gson with Kotlin - and the runtime errors occur far too late here, which may make your program unstable and crash-friendly.这是在 Kotlin 中使用 Gson 时的常见问题 - 运行时错误在这里发生得太晚了,这可能会使您的程序不稳定且容易崩溃。 For example, write:例如,写:

val name: String = p.name

Boom!繁荣! Crash.碰撞。

Gson simply, as per super hacky implementation , allocates memory for the class without calling the constructor, and later fills fields with values that are present in JSON using reflection. Gson 只是按照super hacky implementation ,在不调用构造函数的情况下为类分配内存,然后使用反射用 JSON 中存在的值填充字段。

This makes it possible to store null in Kotlin's not-null properties, and that can cause NPE at runtime.这使得在 Kotlin 的非空属性中存储null成为可能,这可能会在运行时导致 NPE。 You can provide custom TypeAdapter to disable reflection for your class.您可以提供自定义TypeAdapter来禁用您的类的反射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么可以将 java 可空返回值分配给 Kotlin 非可空变量? - Why can a java nullable returned value be assigned to a Kotlin Non-Nullable variable? 从 Kotlin 将 null 传递给不可为空的 Java 方法 - Pass null to non-nullable Java method from Kotlin Kotlin 单元测试变量声明 lateinit vs lazy vs nullable vs non nullable - Kotlin Unit Test variable declaration lateinit vs lazy vs nullable vs non-nullable 你如何让 Mockito 与 Kotlin 不可空类型一起玩得很好? - How do you get Mockito to play nice with Kotlin non-nullable types? java中可以为空的返回值可以放入kotlin中声明为非空的变量中吗 - Can a returned value that can be null in java, be placed into a variable in kotlin which was declared as non null 在 Java 中创建不可为空的类型 - Make non-nullable type in Java 错误:使用 Graphql 启动 Spring 中的不可为空的类型是“ID” - Error : The non-nullable type is 'ID' in Spring Boot with the usage of Graphql Hibernate @OneToMany & @OneToOne 关联到不可为空的实体 - Hibernate @OneToMany & @OneToOne associations to non-nullable entity 使用不可为空值启动可选调用链的优缺点 - Pros and cons of starting an Optional calls chain with a non-nullable 为什么 Kotlin 不能用可空值类型推断此 HashMap 的类型? - Why can't Kotlin infer the type for this HashMap with a nullable value type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM