为什么 Kotlin 数据 class 类型在写入 Firestore 文档时会更改值名称?

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

我在将 Kotlin 数据 class 对象写入云 Firestore 上的文档时遇到了问题。在我假设这是某种错误之前,我想问一下这是否是预期的行为。

我有一个数据class喜欢

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

我直接将它添加到 Firestore,如:

docRef?.add(notification)

但是写入 Firestore 控制台的文档是这样的:

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

写入 Firestore 时,导致布尔值从 isDismissed 变为 dismissed 的原因是什么?

它与 JavaBeans 访问器方法的命名约定有关。使用 Kotlin,class 属性 实际上是使用单独的 getter 和 setter 方法实现的。当查看 class 的代码试图确定底层 JavaBeans 属性的名称时,它将从方法名称中删除“get”、“has”和“is”,然后降低下一个字母的大小写。这就是 Firestore SDK 正在做的事情。

如果您不希望它使用默认行为将访问器方法的名称映射到文档属性的名称,您可以自己使用 key/value 对组合 Map<String, Any> , 或 apply the @PropertyName annotation on the class properties.