androidkotlinparcelabledeep-copy

Android: Using Parcel to Generate a Deep Copy


I was told that it is possible to create a deep copy of an object by writing the object to a parcel, then immediately reading it out again.

So far, I have tried creating a Parcel and writing the object of interest to it as such:

Parcel.obtain().apply {
            setDataPosition(0)
            writeValue(searchRequestParams)
        }

Given that this is the correct way to write an object to a parcel, how can I read out the written object (to complete the deep copy)?


Solution

  • You just need to reset the data position back to zero and then call the reader method. Don't forget to recycle the Parcel object when done.

    Generically you could provide an extension like this:

    inline fun <reified T : Parcelable> T.deepCopy(): T {
      val parcel = Parcel.obtain().apply {
        writeParcelable(this@deepCopy, /* parcelableFlags= */ 0)
        setDataPosition(0)
      }
      
      val result = checkNotNull(parcel.readParcelable<T>(T::class.java.classLoader))
      parcel.recycle()
      return result
    }
    

    Then just use myObject.deepCopy() on any Parcelable type.