如何在我的Realm迁移代码中指定一个盒装字段可以为空?

brw*_*dev 3 android realm kotlin

我正在使用Kotlin,我想在a中添加一个新字段RealmObject,该字段可以为空.这是我在迁移中的内容:

val schema = realm.schema.get(ZOLA_NOTIFICATION)
if (!(schema?.hasField("agentId") ?: false)) {
    schema.addField("agentId", Long::class.java)
}
Run Code Online (Sandbox Code Playgroud)

但是,运行此迁移时收到错误消息:

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().
Run Code Online (Sandbox Code Playgroud)

如何Long::class.java在迁移代码中指定应该是可空类型?

Epi*_*rce 10

不幸,

Long::class.java // kotlin
Run Code Online (Sandbox Code Playgroud)

相当于

long.class // java
Long::class.javaPrimitiveType // kotlin
Run Code Online (Sandbox Code Playgroud)

但是你需要为可以为空的Long in Realm添加的是

Long.class // java
Run Code Online (Sandbox Code Playgroud)

所以你需要使用

Long::class.javaObjectType // Long.class 
Run Code Online (Sandbox Code Playgroud)

在迁移中,您可以使用RealmObjectSchema.setNullable(String field, boolean nullable)方法将必填字段转换为可空字段.