Why Kotlin data classes can have nulls in non-nullable fields with Gson?

This happens because Gson uses an unsafe (as in java.misc.Unsafe) instance construction mechanism to create instances of classes, bypassing their constructors, and then sets their fields directly. See this Q&A for some research: Gson Deserialization with Kotlin, Initializer block not called. As a consequence, Gson ignores both the construction logic and the class state invariants, … Read more

Is it okay to throw NullPointerException programmatically? [closed]

I would recommend you never throw NullPointerException by yourself. The main reason not to do this, as Thorbjørn Ravn Andersen says in a comment below, is that you don’t wan’t to mix ‘real, bad NPEs’ with NPEs thrown intentionally. So, until you’re confident that you’re able to recognize ‘valid’ NPE, I’d recommend to use IllegalArgumentException … Read more