The fault in the stars of Kotlin and Gson

Abhilash Das
AndroidPub
4 min readDec 25, 2019

--

In Kotlin, similar to default values in functions, we can initialize the constructor parameters with some default values.

If the class is initialized with arguments passed, those arguments are used as parameters. However, if the class is initialized without passing argument(s), default arguments are used.

class A (p1:String,p2:String = "P2")

You can initialize the class in two different ways:

val a1 = A("x","y") // p1 = x, p2 = y
val a2 = A("m") // p1 = m, p2 = P2

So far so good.

The real problem comes when you deserialize a JSON let’s say after an API call using Retrofit. To demonstrate the deserialization process, I’ll be using Gson Library instead of making an actual API call.

Let’s check out some scenarios. Try this code in Kotlint REPL. If you are not familiar with Kotlin REPL, then here is a great article that you can refer to. Let’s declare classes in 8 different ways :

class A(
@SerializedName("p1") val p1: String? = "P1",
@SerializedName("p2") val p2: String? = "P2"
)
class B(
@SerializedName("p1") val p1: String? = "P1",
@SerializedName("p2") val p2: String?
)
data class C(
@SerializedName("p1") val p1: String? = "P1"…

--

--