prom85
prom85

Reputation: 17858

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

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()
}

Upvotes: 16

Views: 4396

Answers (2)

sindrenm
sindrenm

Reputation: 3492

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()
)

Upvotes: 15

Doug Stevenson
Doug Stevenson

Reputation: 317712

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
}

Upvotes: 9

Related Questions