tim
02/28/2020, 10:44 AMdata class
object from Google's Firestore. I can save my data class (lets call it Parent) to Firestore, but on retrieval it is a HashMap which seems nontrivial to convert back because some values on Parent are themselves data classes:
data class Parent(val id: String, val child1: Child1, ...)
data class Child1(val name: String)
I can't use GCP's DocumentSnapshot.toObject(Parent::java.class) because for that to work, every field on Parent needs to be nullable, and I'd have to recursively create nullable data class intermediaries (i.e., NullableChild1, etc) ... any suggestions on a better approach? I'm new to Kotlin so figure I'm missing something obvious here 🤷
Example code:
// What i'd like to do
fun getFromFirestore(id): Parent {
...
val data = doc.data()
data.toObject(Parent::java.class) // this throws because it needs a 0 argument constructor to unpack the hash map into
}
// Overly complex solution
fun getFromFirestore(id): Parent {
...
val data = doc.data()
data.toObject(NullableParent::java.class) // this throws because it needs a 0 argument constructor to unpack the hash map into
}
data class NullableParent(val id: String?, val child1: Child1?, ...) {
constructor(): this(null, null) // I could also unpack the hash map here but then this constructor gets verbose!
fun toParent(): Parent {
if(id == null || child1 == null...) throw Error("blah")
return Parent(id, child1, ...) // this doesn't work because Child1 doesn't have a 0 argument constructor so I'd have to create a NullableChild now 😢
}
}
tjohnn
02/28/2020, 8:11 PMtim
02/28/2020, 8:18 PMCzar
02/28/2020, 8:55 PM