Reputation: 460
I have a data class:
data class Temp(
val value: Int
)
When I run the following code:
val temp1 = Gson().fromJson("", Temp::class.java)
val temp2 = temp1.value
println(temp2)
I get null pointer exception.
Doesn't this violate the null safety of kotlin?
Upvotes: 0
Views: 1390
Reputation: 8191
As far as I can remember, this has to do with the way that GSON makes use of reflection, which essentially can bypass kotlin null-safety, so the best thing you can do is mark all fields as potentially nullable and be safe, alternatively you could consider writing custom type adapters too, but that could be a bit much, as this null safety is only really valid for compile-time, but isn't really guaranteed during runtime
Generally, if you're making use of a third-party api which can change at any time, it's probably a good idea to consider the fact that stuff could be changed at any given time, changes in variable names or variables being removed, etc. If you're using your own api's, this is probably a bit different, as you'd (hopefully) have more control over the change, still doesn't hurt to manually implement null-safety though, assume everything can be null
Upvotes: 0