Retrofit skips init { } block of a data class while initializing

A

ahmad

Guest
I'm going to set variables in class Data based on the arguments of DClass

abstract class Data(p: String) {
var a1: String
var a2: String

init {
"""(\w+)(\d+)""".toRegex().find(p)!!.groupValues.run {
a1 = "a1 is ${get(1)}"
a2 = "a2 is ${get(2)}"
}
}
}

data class DClass(val p1: String, val p2: String) : Data(p1)


Then I'm able to get values of a1 and a2 after DClass is created:

DClass("string1", "string2").run { println("$a1 $a2") }


it returns "a1 is string a2 is 1" as it should

Next I'm trying to make retrofit initialize DClass from the proper JSON response: @GET("loadDClass") suspend fun dClass(): DClass

and say the program to do the same output of a1 and a2, it just returns:

"a1 is null a2 is null".

So I found out that init{} block of Data is skipped as the retrofit just builds DClass but doesn't do the initialization

Is it possible to make abstract class' variables be initialized without calling any

Continue reading...
 
Top