Search code examples
androidparcelablekotlin

Android Parcelable in Kotlin


I have such Java parcelable:

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public KwerendaGraficzna createFromParcel(Parcel in) {
        return new KwerendaGraficzna(in);
    }

    public KwerendaGraficzna[] newArray(int size) {
        return new KwerendaGraficzna[size];
    }
};

Now trying to implement it in Kotlin:

companion object {
    @SuppressWarnings("rawtypes")
    val CREATOR: Parcelable.Creator<KwerendaGraficzna!> = object : Parcelable.Creator<KwerendaGraficzna!> {
        override fun createFromParcel(`in`: Parcel): KwerendaGraficzna {
            return KwerendaGraficzna(`in`)
        }

        override fun newArray(size: Int): Array<KwerendaGraficzna!> {
            return arrayOfNulls<KwerendaGraficzna!>(size)
        }
    }
}

arrayOfNulls won't compile requires KwerendaGraficzna while it claims it received KwerendaGraficzna?

So how do I do it?


Solution

  • I suspect you're using an outdated version of Kotlin compiler (since you use !). Here's a version compiling properly with latest version:

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

    Since the Parcelable.Creator requires a public static field we need to mark the CREATOR property with @JvmField and JvmStatic.