Is Kotlin really null safe?
I’m going to tell you step by step how I asked myself this question.
Introduction
In Android, when we need to save data using SharedPreferences or we want to send information from one Activity to another by adding extras in an Intent, we can only send primitive data such as String, Int, Boolean… But if we need to send a more complex object we need to serialize it.
For example, we can save a String by doing the following, but we couldn’t do it with a class object:
Gson is a famous library we can convert objects to Json with and then we can add them as extras in an Intent or save it in SharedPreferences.
How to use Gson to serialize objects
Let the following class be like this:
Let’s create an instance of this class:
Now, using Gson, let’s convert to Json this object:
As the toJson function returns a String, we could solve the initial problem, and we could save the value in a SharedPreferences as follows:
We only need to know how we transform it back to object in order to use it. To do this we are going to use the fromJson function:
objectFromJson is a MyFancyClass type object with the same values as myFancyObject.
Nullability
In Kotlin, by default, all class properties are non-null, as long as they are not defined with?.
Let’s suppose that, for some reason, we have to add a new property to MyFancyClass and it is non-null. For example:
If we get the value of KEY again, as we did before, the behaviour will be surprising:
Since MyFancyClass did not have the fancySecondParam property at the time of saving the value of KEY, the saved Json didn’t have it either. Therefore, when we get it after MyFancyClass modification, it doesn’t know what value to set to the new property. But … surprisingly, in secondObjectFromJson, fancySecondParam is null. And remember that fancySecondParam type is String, which in Kotlin should not support the null value, because it is not String?
The answer to this is that the Gson library is written in Java (at least until the moment of writing these lines), and although the interoperability between Kotlin and Java is great, it’s not perfect. In this case, the library is using String, that in Java can be null. This is what’s happening, and then null is set to a Kotlin String that is supposed not to be null.
So… Be careful when serializing with Gson! :D
I hope it helps you!