0

I have a data class in Kotlin that inherits from a Java class, which defines a constructor with 1 argument,

public BaseClass(String userSessionId) {
    this.userSessionId = userSessionId;
}

My Kotlin class is defined as this

class DerivedClass(
    userSessionId: String,
    var other: Other? = null
) : BaseClass(userSessionId) {

I can't define it as a data class because of userSessionId, which Kotlin requires to be a val or var in data classes. However, if I do so, then Retrofit throws an exception because there are 2 members named userSessionId. Is there a way to have a data class inherit from a Java class with a constructor taking arguments? Note that I cannot change the base class.

A possible solution is to define a dummy val to avoid the name clash, but this is less than ideal

data class DerivedClass(
    val dummy: String,
    var other: Other? = null
) : BaseClass(dummy) {
Francesc
  • 25,014
  • 10
  • 66
  • 84
  • 1
    How about marking the property in `DerivedClass` as [`@Transient`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-transient/index.html)? Retrofit should ignore it as per [this answer](https://stackoverflow.com/a/33557429/4465208). – zsmb13 Nov 30 '17 at 20:17
  • Define it as a val or var and use @SerializedName("userSessionId") before the field in the data class. This should do the trick. – Oknesif Nov 30 '17 at 21:12
  • @zsmb13 Transient works. Please create an answer and I'll accept it. – Francesc Nov 30 '17 at 21:28

1 Answers1

2

You can use the transient keyword in Java to ignore a field during serialization, this can be done in Kotlin by using the @Transient annotation on the property instead.

zsmb13
  • 85,752
  • 11
  • 221
  • 226