Easy way to Parcelize on Kotlin

douglascf

Douglas Fornaro

Posted on January 14, 2021

Easy way to Parcelize on Kotlin

On Android, Parcelable is an interface that a class can implement to be passed within an Intent from an Activity to another one, this way, transporting data from one Activity to another one.

To achieve this your class must implement the Parcelable and override some methods.

data class Product(
    val id: String,
    val title: String,
    val description: String,
) : Parcelable {
    override fun describeContents(): Int {
        TODO("Not yet implemented")
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        TODO("Not yet implemented")
    }
}
Enter fullscreen mode Exit fullscreen mode

Once the class get bigger, you will need to recheck those methods and adapt what is needed to make it continue working.

Thanks to Kotlin, there is an easy way to do this without the needed to override those methods. We just need to use the @Parcelize annotation on the class like this:

@Parcelize
data class Product(
    val id: String,
    val title: String,
    val description: String,
) : Parcelable
Enter fullscreen mode Exit fullscreen mode

This annotation Instructs the Kotlin compiler to generate the writeToParcel(), and describeContents() methods, as well as a CREATOR factory class automatically.

However, to use this annotation you must use the kotlin-parcelize plugin by adding this to your build.gradle file:

plugins {
    ...
    id 'kotlin-parcelize'
}
Enter fullscreen mode Exit fullscreen mode

This is pretty much it to do to start using the @Parcelize on Android!

💖 💪 🙅 🚩
douglascf
Douglas Fornaro

Posted on January 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related