Hello, I have an abstract class `A` and data clas...
# android
d
Hello, I have an abstract class
A
and data class
D
such that :
Copy code
abstract class A {
  //other fields
  open val qty: Int?
}

data class D(
  //other fields
  override val qty: Int?
): A()
now, when I use class
D
for auto-serializing my JSON response using
gson
, I get the following error:
Copy code
java.lang.IllegalArgumentException:class D declares multiple JSON fields named qty
if I’m overriding
qty
- won’t it mean that there is actually only one field called
qty
?
z
I know this isn't the answer but have you tried more modern serializing libraries? Surely they work better with Kotlin
d
Haven't had an issue like this with gson so far, but if this is an actual issue with the library, I’m open to trying out the alternatives.
a
Data classes are not meant to have supertypes, I'll advice you use sealed class or use composition (by interface)
e
abstract val qty
does not create a backing field, only an abstract accessor, so that should help. as opposed to
open val qty
creates a backing field and an open accessor, then
override val qty
creates another backing field (with the same name) and overrides the accessor. JVM considers these to be two distinct fields, there is no such thing as field overriding, and in fact in your case the field
A.qty
is not set by
D.<init>
so it doesn't even have the same value
👍 2
d
Wow, I guess I gotta read more on
open
, thanks for the insight and sure will take a look at Moshi too.
e
well it comes naturally out of the fact that
open
must create a non-
abstract
implementation, which requires a backing field, and that backing field is inaccessible so
override val
must create another one
👍 1