Eitan
Eitan

Reputation: 1032

Best practice and how to implement RealmList that need to support different types of objects

I have a model 'A' that have a list that can be of type 'B' or 'C' and more. I know Polymorphism is not supported by Realm and i cant just do RealmList<RealmObject> or RealmList<? extends RealmObject>.

I just can't figure out how to implement this behavior with Realm.

Upvotes: 1

Views: 417

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

Polymorphism support is tracked here: https://github.com/realm/realm-java/issues/761 , but as long as it isn't implemented you have to use composition instead (https://en.wikipedia.org/wiki/Composition_over_inheritance)

In your case it would look something like this:

public interface MyContract {
  int calculate();
}

public class MySuperClass extends RealmObject implements MyContract {
  private A a;
  private B b;
  private C c;

  @Override
  public int calculate() {
    return getObj().calculate();
  }

  private MyContract getObj() {
    if (a != null) return a;
    if (b != null) return b;
    if (c != null) return c;
  }

  public boolean isA() { return a != null; }
  public boolean isB() { return b != null; }
  public boolean isC() { return c != null; }

  // ...
}

Upvotes: 1

Related Questions