Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
ssuukk Avatar asked Jan 10 '16 08:01

ssuukk


1 Answers

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.

like image 80
miensol Avatar answered Nov 03 '22 14:11

miensol