Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propertly would not be serialize into a Parcel in Kotlin

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)
    }
like image 820
Guillaume agis Avatar asked May 18 '18 15:05

Guillaume agis


People also ask

What is the use of Parcelize in kotlin?

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.

How do you implement Parcelable in kotlin?

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.

Why Parcelable is faster than serializable?

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.

What is Parcelable Android example?

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“.


1 Answers

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 {
    ...
}
like image 107
Alexey Romanov Avatar answered Oct 21 '22 08:10

Alexey Romanov