Search code examples
androidkotlinrealm

Deep copy Realm object in Kotlin


I wanna duplicate realm object and then change the second, without reassigning all the keys. How can I do this? RealmObject does not have .copy() or .clone() methods.

// 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

Solution

  • can you please provide more context and appropriate information as I do not see and array's in your code statement. Thank you.

    EDIT

    Because Money is not a data class, you do not have the auto-generated copy() function available, that leaves you with two options:

    1. Create an custom copy() function in the Money class. This could be mundane if there are huge amount of fields in the class.
    2. Use 3rd party libraries, in which case you'll add external dependency to your RealmObject.

    What I will suggest is a no brainer: Try to convert your Money.class to a Data class. You will get auto generated functions and idiomatically it will work as RealmObjects should be key-values pairs.

    EDIT

    You can use GSON library's serialization/deserialization and hack your way to solve your problem (although this is a hacky way but will do its job):

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

    usage:

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