4

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?

hardysim
  • 2,756
  • 2
  • 25
  • 52

1 Answers1

4

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.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Hmm, so to make this clear (your text is confusing): A `RealmList` *cannot* contain `null` but one with `Integer` can? And if I want to use this kotlin-non-null-type I *have to* add `@Required`? This would be fine for me. THX. – hardysim Dec 23 '17 at 10:57
  • No, I meant that @Required means you can't store null as an Integer – EpicPandaForce Dec 23 '17 at 12:09
  • confusion complete... is the following correct? When using `Integer` I *could* use `null` but adding `@Required` prevents this / using `Int` (without `?`) cannot use `null` by default. Right? But when I don't want `nulls`, why do I need `@Require` when using `Int`? Is it because `Int` and `Integer` are equal for Realm? So what`s correct then when I want non-null-int values? – hardysim Dec 23 '17 at 18:16
  • For a RealmList of primitive, required specified whether you can store `Null` as a value inside the list. – EpicPandaForce Dec 24 '17 at 10:30