Mayank
Mayank

Reputation: 259

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?

Upvotes: 2

Views: 1633

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81539

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

Upvotes: 0

Christian Melchior
Christian Melchior

Reputation: 20126

Polymorphism and inheritance are not supported by Realm. You can follow this issue for updates: https://github.com/realm/realm-java/issues/761

Generally we recommend Composition instead: https://en.wikipedia.org/wiki/Composition_over_inheritance, but in your situation that probably isn't ideal since it would look something like this:

public class IBaseA extends RealmObject { ChildA childA; ChildB childB; }

Upvotes: 2

Related Questions