Kotlin 中的深拷贝 Realm 对象

Deep copy Realm object in Kotlin

我想复制领域对象然后更改第二个,而不重新分配所有键。我怎样才能做到这一点? RealmObject 没有 .copy().clone() 方法。

// Money is not data class and has ∞ fields which will be boring to re-assign

val money = Money()
money.amount = 1000

...

val anotherMoney = money
anotherMoney.amount = 500

println(money.amount) // prints 500

您能否提供更多上下文和适当的信息,因为我在您的代码语句中没有看到和数组。谢谢。

编辑

因为 Money 不是数据 class,您没有可用的自动生成的 copy() 函数,因此您有两个选择:

  1. 在 Money class 中创建自定义 copy() 函数。如果 class.
  2. 中有大量字段,这可能很普通
  3. 使用第 3 方库,在这种情况下,您将向 RealmObject 添加外部依赖项。

我的建议很简单:尝试将您的 Money.class 转换为数据 class。您将获得自动生成的函数,并且惯用地它将起作用,因为 RealmObjects 应该是键值对。

编辑

您可以使用 GSON 库的 serialization/deserialization 并破解您的方法来解决您的问题(虽然这是一种破解方法,但会完成它的工作):

fun clone(): Money {
  val stringMoney = Gson().toJson(this, Money::class.java)
  return Gson().fromJson<Money>(stringMoney, Money::class.java)
}

用法:

val originalMoney = Money()
val moneyClone = originalMoney.clone()