androidrealmrealm-java

Polymorphic relations in realm


IBaseA   <--- Interface
CBaseB   <--- Concrete base class

ChildA implements IBaseA{
    //fields and getters, setters
}

ChildB extends CBaseB, implements IBaseA{
    //fields and getters, setters  
}

TestClass implements RealmModel{
    private IBaseA child_obj;
}

The intention for making TestClass this way was to be able to assign any of ChildA or ChildB objects to TestClass.child_obj, and still be able to let ChildA and ChildB implement other interfaces as required.

However, this causes a compile-time exception

Error:(12, 8) error: Type 'in.avanti_app.student_companion.realmClasses.TestClass' of field 'child_obj' is not supported

How we can achieve the above intention?


Solution

  • Create a RealmObject for each concrete class, flattening the bases into the RealmObjects. Share the field accessors with common interfaces.

    Read this github comment

    and

    Composition over inheritance for RealmObjects with Gson serialization