Kotlin – Illusion of non nullable type

Kotlin promises non nullable types to avoid the billion dollar Null pointer exception. However, this isn’t always the case especially when using Java based libraries working with Kotlin base data structures.

Here is a Kotlin data class declaring all non-nullable types

IDE supporting Kotlin and Kotlin compiler wouldn’t allow a version of User with null values at compile time. However, that doesn’t necessarily mean all User instances are null safe at runtime. This is especially the case when dealing with Java based libraries using reflection to create an instance of User. Should the json representation of the user not have last name, it would end up creating an instance of User with null values.

This would eventually fail any Kotlin code trying to access lastName with a null pointer exception. Kotlin compile and tools can only do so much when dealing with Java based libraries, a gotchas for Kotlin newbies.