Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using android-extensions`s Parcelize annotation on objects that extends Parceable sealed classes

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)
    }

}
like image 967
ademar111190 Avatar asked Aug 16 '18 19:08

ademar111190


People also ask

Can sealed class be Parcelable?

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 .

How do I use kotlin-Parcelize annotation?

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.

What is Android Parcelize?

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.

How do you Parcelize a data class?

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…


1 Answers

You need to make sure that you have you Kotlin up to date.

You can follow an example here.

like image 133
abdelali eramli Avatar answered Sep 28 '22 07:09

abdelali eramli