Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
    }
}
like image 228
Daniel Avatar asked Oct 27 '17 15:10

Daniel


1 Answers

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

like image 57
Alexey Romanov Avatar answered Sep 19 '22 16:09

Alexey Romanov