Colton Idle

11/17/2021, 2:02 AM
I'm using firestore sdk for android which allows me to take a response and turn it into an object. My data class is defined as
data class Person(
    val name: String = "",
but if firestore sends
, then even though the type is non-null, if I put a breakpoint... I can see that I do actually get a null value? Question: How can a non-null property like
be null? I'm assuming this is because of reflection/java-interop or something?

Stephan Schroeder

11/17/2021, 7:35 AM
I don't know anything about firestore/android, but if you think that java interop could be the issue here, than it's probably due to platform types. E.g. if you get a String from java code, it's Kotlin type will be
. You can't create that type in Kotlin, only by java interop, and the thing is: the compiler will trust you, when you say it's not nullable! So
val platformStr: String! = someJavaFunction()
val nullableStr: String? = someKotlinFunction()

val s1: String = nullableStr // Compiler error! can't assign a nullable variable to a non-nullable one

val s2: String = platformStr // no Compiler error, but maybe still null!!! but the compiler trusts you to have more knowledge about the code then itself can deduce
So if you invoke java code and sometimes it returns
then set the type as nullable, so you're forced to handle the null-case. You can also check other articles on this topic, like this one
In a prior project I've configured Jackson as json parser (together with its KotlinModule) to create non-nullable types and it would simply discard all data that didn't conform to the nullability of the types. If you prefer discarding non-conforming data or first accept it as nullable and then do manual checks/filtering is up to you (/your use case). If you can select your own deserialisation lib (instead of being stuck with one written in java), Kotlin Serialisation ( might be an option to look at.