0

In my Android Kotlin project, I have an abstract class and a child class that inherits the abstract class:

abstract class AbstractExample(
    val test2: String,
    val test3: String) : Parcelable
@Parcelize
class Example(
    val test1: String,
    test2: String,
    test3: String) : AbstractExample(test2, test3)

Because I want my Example class to be parcelable, I use the @Parcelize annotation.

The problem is: I get the following error on test2 and test3 in the Example class:

'Parcelable' constructor parameter should be 'val' or 'var'.

So to fix that, I tried the following:

abstract class AbstractExample(
    open val test2: String,
    open val test3: String) : Parcelable
@Parcelize
class Example(
    val test1: String,
    override val test2: String,
    override val test3: String) : AbstractExample(test2, test3)

Now it compiles, but then I get a new problem: if I want to use Gson to convert the Example class to JSON (so I can send it to a webservice, for example), then I get the following error:

Example declares multiple JSON fields named test2

How can I then fix my two classes so I can parcelize my Example class, and also be able to convert it into JSON using Gson?

Thanks.

matteoh
  • 2,810
  • 2
  • 29
  • 54

1 Answers1

1

A little research lead me to this, so here is how to fix it:

abstract class AbstractExample(
    @Transient open val test2: String,
    @Transient open val test3: String) : Parcelable
@Parcelize
class Example(
    val test1: String,
    override val test2: String,
    override val test3: String) : AbstractExample(test2, test3)
matteoh
  • 2,810
  • 2
  • 29
  • 54