Data class with optional params

Viewed 35

I am working on an Android app and I am trying to find a way to a data class which contain optional parameters. the data class is a part of Retrofit command so, when the params is not there, I do not want him to be sent.

data class Status(
    @field:com.google.gson.annotations.SerializedName("power") val power: Int?,
    @field:com.google.gson.annotations.SerializedName("state") val state: Int?
)

So basically, I would expect the outpout to be either:

{
   "power": 1
}

or

{
   "state": 45
}

or

{
   "power": 1,
   "state": 45
}

and the data class must be respectively called as:

Status(power=1) or Status(state=45) or Status(power=1, status=45)

Any idea ? I am will have multiple params and I would like to prevent writing a class for every cases

As of now, I have a error when using it as for example I am only doing Status(power=1) so it complains that the params state is missing.

Thanks

1 Answers

You should have a default value for the param you want to make it as optional. So here ,you can make it something like -1 or null

data class Status(
    @field:com.google.gson.annotations.SerializedName("power") val power: Int? = -1,
    @field:com.google.gson.annotations.SerializedName("state") val state: Int? = -1
)

Or

data class Status(
    @field:com.google.gson.annotations.SerializedName("power") val power: Int? = null,
    @field:com.google.gson.annotations.SerializedName("state") val state: Int? = null
)

So you can call Status constructor with any of the like below.

Status() // Power & State will have default values
Status(1) (or) Status(power = 1)  //Power = 1 and state will have default value
Status(state = 45) //Power will have default value and state = 45
Status(1,45) (or) Status(power=1,state=100) (or) Status(state=45,power=1)// Power=1,State =45

If you have default only you can make it as optional. And if you have made all the fields having some default value, you can create object from empty constructor also of the data class.

Hope it helps .

Related