0

I have a Result parcelable class that is supposed to serve as a container for a key and a parcelable data. This is how I define it:

@Parcelize
open class Result<out T : Parcelable>(val key: String, val data: T?) : Parcelable

The problem is that when defining the child class, in order for @Parcelize to work, I need to add val to the object in the constructor, essentially making the data being written twice to the parcel twice. Here is an example:

@Parcelize
class LessonFinishedResult(private val lessonActivityData: LessonActivityData) :
    Result<LessonActivityData>(LessonActivityData.LESSON_KEY, lessonActivityData), Parcelable

I would like to have this:

@Parcelize
class LessonFinishedResult(lessonActivityData: LessonActivityData) :
    Result<LessonActivityData>(LessonActivityData.LESSON_KEY, lessonActivityData), Parcelable

But it is not allowed. Is there a smart way I can get around this? And another thing, is there a way I can avoid having to manually use Result<LessonActivityData> and have the type be inferred automatically from the object being passed?

Thanks!

1 Answers1

0

essentially making the data being written twice to the parcel twice

It isn't; the code generated by @Parcelize doesn't care about the superclass at all. It can even not be Parcelizable. Only the primary constructor parameters (in this case val lessonActivityData) are written/read, and when reading it's enough to pass the correct parameters to the superclass constructor.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487