Mr.Drew
Mr.Drew

Reputation: 1109

Why does Kotlin data class type change a value name when writing to a Firestore Document?

I've encountered an issue with writing a Kotlin data class object to a document on cloud Firestore. Before I assume this is some sort of bug, I want to ask if this is intended behavior.

I have a data class like

data class Notification(
    val createdAt: Timestamp?,
    val isDismissed: Boolean?,
    val text: String?
)

I add it directly to Firestore like:

docRef?.add(notification)

But the document that gets written to Firestore console is this:

    createdAt: month number, 2020 at time AM/PM UTC+8
    dismissed: false
    text: "My text."

What is causing the boolean value to change from isDismissed to dismissed when writing to Firestore?

Upvotes: 0

Views: 730

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317712

It has to do with the naming conventions for JavaBeans accessor methods. With Kotlin, a class property is actually implement with separate getter and setter methods. When code that looks at the class attempts to determine what the names of the underlying JavaBeans properties are, it will strip off "get", "has", and "is" off the name of the method, then lower the case of the next letter. This is what the Firestore SDK is doing.

If you don't want the default behavior that it uses to map names of accessor methods to the names of document properties, you can either compose a Map<String, Any> on your own with key/value pairs, or apply the @PropertyName annotation on the class properties.

Upvotes: 3

Related Questions