I wish to have my variables that are not from my constructor, part of my Parcelable. However, I face this warning "Propertly would not be serialize into a Parcel", that inform me I can't do that currently.
I am using Kotlin in experimental v.1.2.41.
How can I do ?
@Parcelize
data class MyClass(private val myList: List<Stuff>) : Parcelable {
val average: List<DayStat> by lazy {
calculateAverage(myList)
}
The kotlin-parcelize plugin provides a Parcelable implementation generator. @Parcelize requires all serialized properties to be declared in the primary constructor. The plugin issues a warning on each property with a backing field declared in the class body.
The first step is adding the kotlin-parcelize plugin to the shared module build. gralde file, till being able to use Parcelize annotation: As you know in regular Android projects if we want to make a class Parcelable, we should add the Parcelize annotation to it and implement the Parcelable interface.
Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn't create more temp objects while passing the data between two activities.
Parcelable is a serialization mechanism provided by Android to pass complex data from one activity to another activity.In order to write an object to a Parcel, that object should implement the interface “Parcelable“.
Do you want to make it a part of Parcelable
(just mark @Transient
) or to write it to the parcel?
In the second case the design document explains why this is a problem (search for "Properties with initializers declared in the class body") and laziness only makes the meaning less clear.
If you can live without laziness, you can do this:
@Parcelize
data class MyClass (private val myList: List<Stuff>, val average: List<DayStat> = calculateAverage(myList)) : Parcelable {
...
}
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