I'm using Kotlin and I want to add a new field to a RealmObject
and that field can be nullable. Here's what I have in my migration:
val schema = realm.schema.get(ZOLA_NOTIFICATION)
if (!(schema?.hasField("agentId") ?: false)) {
schema.addField("agentId", Long::class.java)
}
However, I receive an error message when this migration is run:
Non-fatal Exception: io.realm.exceptions.RealmMigrationNeededException
Field 'agentId' does not support null values in the existing Realm file. Either set @Required, use the primitive type for field 'agentId' or migrate using RealmObjectSchema.setNullable().
How do I specify that the Long::class.java
should be the nullable type in the migration code?
Unfortunately,
Long::class.java // kotlin
is equivalent to
long.class // java
Long::class.javaPrimitiveType // kotlin
But what you need to add for nullable Long in Realm is
Long.class // java
So you need to use
Long::class.javaObjectType // Long.class
In migration, you can turn a required field to nullable field using RealmObjectSchema.setNullable(String field, boolean nullable)
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With