I've been developing a Kotlin back-end service, and stumbled across the Firestore documentSnapshot.toObject(className::class.java)
method.
Take the following Kotlin data class
:
data class Record(
val firstName: String = "",
val lastName: String = "",
val city: String = "",
val country: String = "",
val email: String = "")
And the following code from my Repository
class:
if (documentSnapshot.exists()) {
return documentSnapshot.toObject(Record::class.java)!!
}
Now, from what I understand the method documentSnapshot.toObject(className::class.java)
requires and invokes a no-param default constructor, e.g. val record = Record()
.
This invocation would invoke the primary constructor and assign the default values stated in it (in the case of the data class Record
, the empty strings ""
) to the fields.
Then, it uses public setter methods to set the instance's fields with the values found in the document
.
How this is possible, given that the fields have been marked as val
in the primary data class constructor?
Is reflection at play here?
Is val
not truly final in Kotlin?