Parcelable 不保存变量

Parcelable not saving variable

我有一个实现 Parcelable 的数据 class,其中它的所有字段都被保存到 Parcel,构造函数外部的变量除外。

我的class:

data class MyParcelableClass(
    val fieldA: String,
    val fieldB: Int,
    val fieldC: AnotherParcelableClass
) : Parcelable {

    // This is the one I'm having problems with
    var troublesomeVariable: TroublesomeParcelableClass? = null
        set(value) {
            field = value
            if (field != null)
                // do stuff (irrelevant to the question)
        }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.run {
            writeString(fieldA)
            writeInt(fieldB)
            writeParcelable(fieldC, flags)
            writeParcelable(troublesomeVariable, flags) 
            /*
             * At this point, troublesomeVariable is null, 
             * even though a value has already been assigned
             */
        }
    }

    override fun describeContents() = 0

    companion object CREATOR : Parcelable.Creator<MyParcelableClass> {
        override fun createFromParcel(source: Parcel): MyParcelableClass {
            val fieldA = source.readString()!!
            val fieldB = source.readInt()
            val fieldC = source.readParcelable<AnotherParcelableClass>(AnotherParcelableClass::class.java.classLoader)!!
            val troublesomeVariable = source.readParcelable<TroublesomeParcelableClass>(TroublesomeParcelableClass::class.java.classLoader)!!
            /*
             * Since troublesomeVariable has been written as null to the parcel,
             * it will obviously be null here as well
             */

            return MyParcelableClass(fieldA, fieldB, fieldC).also {
                it.troublesomeVariable = troublesomeVariable
            }
        }

        override fun newArray(size: Int): Array<MyParcelableClass?> = arrayOfNulls(size)
    }

}

如代码中的注释所示,问题是该变量已作为 null 写入包裹,即使它已经分配了一个值 - 我放置了大量日志和断点以确保该变量在 parcelising 之前不是 null,实际上它不是。

总而言之,我想知道我需要做什么才能将该变量成功写入包裹,然后像其他人一样检索它。任何帮助将不胜感激。

Kotlin 的数据 类 与 Java 的 POJO 具有相同的行为:您在构造函数中初始化所有字段并具有 getters(和 setters ,视需要而定)。

当数据 类 实现 Parcelable 时,实际上只有构造函数中包含的字段被写入和读取 Parcel - 我通过使用 [=12= 实现了它] 注释而不是我的手动实现,IDE 显示提示告诉我用 @IgnoredOnParcel.

注释 troublesomeVariable

所以解决方案是将 troublesomeVariable 作为 private var 包含在构造函数中并手动实现其 getter 和 setter,就像在 Java 中一样, 它奏效了。