Home > Blockchain >  How to create from parcel with Kotlin @Parcelize?
How to create from parcel with Kotlin @Parcelize?

Time:04-11

I'm trying to migrate parcelable model from Java to Kotlin.

My model looks like this:

import kotlinx.parcelize.*

@Parcelize
class SignatureAuthorityModel
    (var id: Int,
    var cloudId: Int,
    var uuid: UUID?): android.os.Parcelable
{
    override fun equals(other: Any?): Boolean
    {
        //equals implementation
    }

    override fun hashCode(): Int
    {
       //some hash implementation
    }

    override fun toString(): String
    {
       //some stringifier implementation
    }
}

I can call writeToParcel for this model, but SignatureAuthorityModel.createFromParcel(parcel) isn't available. Must I write it separately, or must I configure kotlin-parcelize plugin somehow? From kotlin documentation it seems that createFromParcel should also be generated automatically when I use @Parcelize annotation, and that I must write implementation in companion object Creator only if I have some advanced logic. What is the proper way to do it?

CodePudding user response:

If you are using @Parcelize annotation then you don't need to write createFromParcel method. Because @Parcelize manages createFromParcel method internally.

just write your data class like below. And might be you wrong import for Parcelable and your class should be like below.

import kotlinx.parcelize.Parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable

CodePudding user response:

It seems to be a known issue that the creator is not accessible when using @Parcelize

See this issue created 5 years ago: https://youtrack.jetbrains.com/issue/KT-19853

Following the comments there it doesn't seem like they are doing anything about it.

My personal opinion is that they probably don't bother about it because for the most common use case it's not necessary. The most common use case for Parcelable in Android development is to pass the objects from one Activity to another using intent.putExtra() or intent.putParcelableArrayListExtra() and in that case the the turning into Parcel and back happens automatically.

EDIT:
hmm.. actually they mention here https://github.com/JetBrains/kotlin/pull/4575 that it should be available using parcelableCreator but I can't figure out how to use it or if it's even actually in the latest version

  • Related