2

Frequently I see code snippets like this:

public RealmResults<MyObject> getMyObjects(List<Integer> ids) {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        RealmQuery<MyObject> query = realm.where(MyObject.class);
        for (int i=0; i< ids.size(); i++) {
            query = query.equalTo("id", ids.get(i));
            if (i != ids.size() -1) {
                query = query.or();
            }
        }
        return query.findAll();
    } finally {
        if (realm != null) realm.close();
    }
}

Is it really necessary to reassign the output of a query operator to the RealmQuery object? Will this other snippet achieve the same result? (hint: i have removed query = before the calls to .equalTo() and .or())

public RealmResults<MyObject> getMyObjects(List<Integer> ids) {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        RealmQuery<MyObject> query = realm.where(MyObject.class);
        for (int i=0; i< ids.size(); i++) {
            query.equalTo("id", ids.get(i));
            if (i != ids.size() -1) {
                query.or();
            }
        }
        return query.findAll();
    } finally {
        if (realm != null) realm.close();
    }
}
Marco Romano
  • 1,169
  • 7
  • 24

1 Answers1

2

The query essentially functions like a builder, so in reality, the returned builder has its state set with the given condition. This means that the assignment is optional.

This is why queries like the structure of the one below work:

query.equalTo(...).equalTo(...).beginGroup()....endGroup().findAll()

The returned parameter is this and not a new RealmQuery.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Thanks I was adding a comment to the previous answer you downvoted but it has disappeared. I looked at the implementation of `equalTo()` and it ends with `return this`: I thought it must then modify the state of the same RealmQuery object it was invoked onto (via side effects). If this is true is it ok to entail that reassignment is not needed therefore? – Marco Romano Aug 26 '16 at 07:43
  • You are correct, the reassignment is not needed. It's just there for clarity I think. – EpicPandaForce Aug 26 '16 at 07:44
  • I had this question once and read through the source, so it's true :) – EpicPandaForce Aug 26 '16 at 07:45