Kotlin meets gson

Kotlin pitfalls

During my work I found a way to trick Kotlin and put null into not nullable variable.

Lets define data class in Kotlin:

and its representation in json:

Now we can deserialize it like this:

What will happen if we try to deserialize following string?

address field is set as not nullable, but with value of null. WAT?

What happened is that Gson creates object using default constructor (with no parameters) and than tries to fill the fields that are in json. If something is missing it stays as null.

So what to do now? well only use non-null types if you are 100% sure, that json that contains that fields are filled. and our Person class should looke like this:

If you are, like me, a fan of fail early paradigm then you can use copy function to validate object (as suggested by mandrizzle):

Also please lookout for automatic json to object conversion f.e. using Retrofit!

– Updates based on feedback on reddit:

  • how gson works
  • using copy function to fail early.