Douglas Fornaro
Posted on January 14, 2021
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")
}
}
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
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'
}
This is pretty much it to do to start using the @Parcelize
on Android!
Posted on January 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.