I'm using kotlin android extensions to auto generate my Parcelables, but given the following code I'm getting 'Parcelable' should be a class
.
the code:
sealed class Action : Parcelable
@Parcelize
object Run : Action()
@Parcelize
data class Ask(
val question: String
) : Action()
My understanding is that it is impossible to use @Parcelize
in an object
(Once it is working on the Ask class) in the way I'm doing it.
I want to use the Parcelable
annotation in an object that extends a sealed class
, so I'm do not know how to do it and do not write the following boilerplate.
object Run : Action() {
override fun writeToParcel(p0: Parcel?, p1: Int) {}
override fun describeContents() = 0
@JvmField
val CREATOR = object : Parcelable.Creator<Run> {
override fun createFromParcel(parcel: Parcel) = Run
override fun newArray(size: Int) = arrayOfNulls<Run?>(size)
}
}
Parcelize sealed classessealed and abstract classes can also be parcelized. For this, the parent class needs to implement Parcelable and all the child classes need to be annotated with @Parcelize .
Just add the @Parcelize annotation to a class implementing the Parcelable interface and the Parcelable implementation will be generated automatically. This is the same example as in the previous article, in just 2 lines of code. The class can be a data class but it's optional.
In Android, to pass the data from one activity to another activity, we use the Parcelable. The kotlin-parcelize plugin provides a Parcelable implementation generator. The Android's Parcelable is an interface on which, the values can be written and read from a Parcel.
All you need to do is add @Parcelize annotation to the data class to make it Parcelable. That's all. You can send your data object from source activity like this… and receive the data in your destination activity through the Intent like this…
You need to make sure that you have you Kotlin up to date.
You can follow an example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With