Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

How is this possible? The name attribute is not a nullable string.

like image 309
Vinicius E. Andrade Avatar asked Jan 22 '20 17:01

Vinicius E. Andrade


Video Answer


1 Answers

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. 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.

This makes it possible to store null in Kotlin's not-null properties, and that can cause NPE at runtime. You can provide custom TypeAdapter to disable reflection for your class.

like image 116
xinaiz Avatar answered Oct 10 '22 15:10

xinaiz