Android: error: non-static type variable T cannot be referenced from a static context

Viewed 1676

I have the following class:

@Parcelize
data class Collection<T : Parcelable> constructor(
    var models: List<T>,
    var cursor: String?
) : Parcelable

When I was using Kotlin 1.4.10, the project builds correctly without any errors, then I updated the project to Kotlin 1.4.21, and migrated to use kotlin-parcelize instead of kotlin-android-extensions, so after Kotlin update, when building the project I get the following errors:

> Task :domain:kaptDebugKotlin FAILED
/Library/DevelopmentArea/workspace/baaz_android_new/clean_domain/domain/build/tmp/kapt3/stubs/debug/com/myapp/domain/model/Collection.java:101: error: non-static type variable T cannot be referenced from a static context
        public final com.myapp.domain.model.Collection<T>[] newArray(int size) {
                                                                   ^/Library/DevelopmentArea/workspace/baaz_android_new/clean_domain/domain/build/tmp/kapt3/stubs/debug/com/myapp/domain/model/Collection.java:110: error: non-static type variable T cannot be referenced from a static context
        public final com.myapp.domain.model.Collection<T> createFromParcel(@org.jetbrains.annotations.NotNull()

Note: I'm using Android Studio 4.1.1

1 Answers

Currently to fix the errors that I get, and meanwhile, keep using Kotlin 1.4.21, I just removed the @Parcelize annotation from any class with a generic type usage like the one in the question, and just implemented the Parcelable with the old way like the following:

    data class Collection<T> constructor(
    var models: List<T>,
    var cursor: String?
) : Parcelable {

    constructor(parcel: Parcel) : this(
        mutableListOf<T>().also { list: List<T> ->
            parcel.readList(list, Collection<T>::models.javaClass.classLoader)
        },
        parcel.readString())

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeList(models)
        parcel.writeString(cursor)
    }

    override fun describeContents(): Int = 0

    companion object {

        @JvmField
        val CREATOR = object : Parcelable.Creator<Collection<Parcelable>> {
            override fun createFromParcel(source: Parcel): Collection<Parcelable> {
                return Collection(source)
            }

            override fun newArray(size: Int): Array<Collection<Parcelable>?> {
                return arrayOfNulls(size)
            }
        }
    }
}
Related