9

I have something similar like the following where I want to pass them around as intent arguments;

sealed class BasketType : Parcelable {

    class BasketOne(val basketId: String): BasketType() {

        constructor(parcel: Parcel) : this(parcel.readString()) {
        }

        override fun writeToParcel(parcel: Parcel, flags: Int) {
            super.writeToParcel(parcel, flags)
            parcel.writeString(basketId)
        }

        override fun describeContents(): Int {
            return 0
        }

        ...
    }

    ...
}

But I get the following error;

Abstract member cannot be accessed directly

on the line super.writeToParcel(parcel, flags) which is kind of expected.

I've looked around for a workaround but could not find one. Any ideas?

stdout
  • 2,471
  • 2
  • 31
  • 40

2 Answers2

72

if you want @Parcelize in sealed class, do it like this:

sealed class AssistantType : Parcelable{
    @Parcelize data class Dashboard(
        val firstName: String,
        val hasGoal: Boolean,
        val hasOverDuePayment: Boolean
    ) : AssistantType()

    @Parcelize data class Detail(
        val firstName: String,
        val isGoalAchived: Boolean
    ) : AssistantType()
}

and Add below code into your App Level gradle.

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

androidExtensions {
    experimental = true
}
Boken
  • 4,825
  • 10
  • 32
  • 42
Adnan Abdollah Zaki
  • 4,328
  • 6
  • 52
  • 58
3

You simply leave out the super call. There is no super implementation of that function, which is why it's complaining.

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(basketId)
}

the super call is only there because the code generation of android studio puts it there without checking that it's actually possible.

zapl
  • 63,179
  • 10
  • 123
  • 154