不允许覆盖 'writeToParcel'。改为使用 'Parceler' 伴随对象

Overriding 'writeToParcel' is not allowed. Use 'Parceler' companion object instead

我使用了 Jetbrains plugin for generating Android Parcelable class in Kotlin, and got these two exceptions (not warnings, unlike ,所以项目没有构建):

CREATOR_DEFINITION_IS_NOT_ALLOWED: 'CREATOR' definition is not allowed. Use 'Parceler' companion object instead.

OVERRIDING_WRITE_TO_PARCEL_IS_NOT_ALLOWED: Overriding 'writeToParcel' is not allowed. Use 'Parceler' companion object instead.

我已经看过类似的问题,但没有找到适合我的案例的解决方案。

我的 Kotlin 版本:1.1.51(根据 Gradle),但此功能是在 1.1.4 中添加的:https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-1-4-is-out/

自动生成的代码:

@Parcelize
data class User(
        val id: Int,
        val cardId: String,
        val coefficent: Float = 1.0F,
        val name: String,
        val surname: String = ""
) : Parcelable {
    constructor(source: Parcel) : this(
            source.readInt(),
            source.readString(),
            source.readFloat(),
            source.readString(),
            source.readString()
    )

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<User> = object : Parcelable.Creator<User> {
            override fun createFromParcel(source: Parcel): User = User(source)
            override fun newArray(size: Int): Array<User?> = arrayOfNulls(size)
        }
    }

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeInt(id)
        writeString(cardId)
        writeFloat(coefficent)
        writeString(name)
        writeString(surname)
    }
}

您可以使用@Parcelize告诉编译器添加方法,显式实现它们(由IDEA插件与否,没关系)。两者同时拥有是没有意义的。

您可以自定义@Parcelize使用的逻辑,但仍然不是通过覆盖方法来完成的,而是如https://github.com/Kotlin/KEEP/blob/master/proposals/extensions/android-parcelable.md#custom-parcelables中所述(这就是消息的"Use 'Parceler' companion object instead"部分的意思).