Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a boxed field can be nullable in my Realm migration code?

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?

like image 486
brwngrldev Avatar asked Jun 10 '17 12:06

brwngrldev


1 Answers

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.

like image 59
EpicPandaForce Avatar answered Jan 22 '23 02:01

EpicPandaForce