Search code examples
androidkotlinrealmrealm-migration

RealmMigrationNeededException when adding RealmList<Int> (Kotlin)


I want to add a primitive list to an existing model but I get an exception.
Attention: This is all done it Kotlin.

Here's the model:

open class Foo(
    @PrimaryKey var id: Int = 0
) : RealmObject()

Now I want to add the following field:

var idList: RealmList<Int> = RealmList()

This could be an empty list so I initialize it with a blank RealmList (which used to work for non-primitive-list-fields).

My migration looks like this:

schema.get("Foo")
        ?.addRealmListField("idList", Int::class.java)

When running the app, I get an RealmMigrationNeededException:

Migration is required due to the following errors:
- Property 'Foo.idList' has been made optional.


I can work around this by adding @Required to the new field in the model but I'm not sure if the list can still be empty / null then.

What's the correct way to add a primitive-list to a model and whats the correct migration for this?


Solution

  • Actually, your migration is correct. If you don't want the list to be able to contain null as a value (considering it is a RealmList<Integer>, where Integer can be null), you should add @Required annotation.