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

时间:2017-06-10 12:26:20

标签: android realm kotlin

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

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

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

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().

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

1 个答案:

答案 0 :(得分:9)

不幸的是,

Long::class.java // kotlin

相当于

long.class // java
Long::class.javaPrimitiveType // kotlin

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

Long.class // java

所以你需要使用

Long::class.javaObjectType // Long.class 

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