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

1

8

I used Jetbrains plugin for generating Android Parcelable class in Kotlin, and got these two exceptions (not warnings, unlike here, so the project doesn't build):

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.

I have looked through similar questions, and didn't find any solutions for my case.

My Kotlin version: 1.1.51 (according to Gradle), but this feauture was added in 1.1.4: https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-1-4-is-out/

The auto-generated code:

@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)
    }
}
Bushwa answered 27/10, 2017 at 15:30 Comment(0)
H
6

You can either use @Parcelize to tell the compiler to add the methods, or implement them explicitly (generated by IDEA plugin or not, it doesn't matter). It doesn't make sense to have both at once.

You can customize logic used by @Parcelize, but it's still not done by overriding the methods, but as described in https://github.com/Kotlin/KEEP/blob/master/proposals/extensions/android-parcelable.md#custom-parcelables (that's what the "Use 'Parceler' companion object instead" part of the message means).

Hypothesis answered 27/10, 2017 at 16:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.