Firestore - how to exclude fields of data class objects in Kotlin

久未见 提交于 2020-05-14 15:15:28

问题


Firestore here explains, how I can use simple classes to directly use them with firestore: https://firebase.google.com/docs/firestore/manage-data/add-data

How can I mark a field as excluded?

data class Parent(var name: String? = null) {
    // don't save this field directly
    var questions: ArrayList<String> = ArrayList()
}

回答1:


Since Kotlin creates implicit getters and setters for fields, you need to annotate the setter with @Exclude to tell Firestore not to use them. Kotlin's syntax for this is as follows:

data class Parent(var name: String? = null) {
    // questions will not be serialized in either direction.
    var questions: ArrayList<Child> = ArrayList()
        @Exclude get
}



回答2:


I realize this is super late, but I just stumbled upon this and thought I could provide an alternative syntax, hoping someone will find it helpful.

data class Parent(var name: String? = null) {
    @get:Exclude
    var questions: ArrayList<Child> = ArrayList()
}

One benefit to this is that, in my opinion, it reads a little clearer, but the main benefit is that it would allow excluding properties defined in the data class constructor as well:

data class Parent(
    var name: String? = null,
    @get:Exclude
    var questions: ArrayList<Child> = ArrayList()
)


来源:https://stackoverflow.com/questions/49224070/firestore-how-to-exclude-fields-of-data-class-objects-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!