I have the following data class in Kotlin:
import com.google.gson.annotations.SerializedName
data class RouteGroup(
@SerializedName("name") var name: String,
@SerializedName("id") var id: Int
)
Sometimes I need to create an object with both fields, sometimes with only one of them.
How can I do this?
EDIT
This is not the duplicate of this question: Can Kotlin data class have more than one constructor? That question shows how to set a default value for a field. But in my case, I don't need to serialize the field with the default value. I want a field to be serialized only when I explicitly assign a value to it.
it is easy you have to use the nullable operator
import com.google.gson.annotations.SerializedName
data class RouteGroup @JvmOverloads constructor(
@SerializedName("name") var name: String? = null,
@SerializedName("id") var id: Int? = null
)
You may need something like this:
sealed class RouteGroup
data class RouteGroupWithName(
@SerializedName("name") var name: String
) : RouteGroup()
data class RouteGroupWithId(
@SerializedName("id") var id: Int
) : RouteGroup()
data class RouteGroupWithNameAndId(
@SerializedName("name") var name: String,
@SerializedName("id") var id: Int
) : RouteGroup()
EDIT 1:
Or you can use nullable fields and named parameters like this:
data class RouteGroup(
@SerializedName("name") var name: String? = null,
@SerializedName("id") var id: Int? = null
)
val routeGroupWithName = RouteGroup(name = "example")
val routeGroupWithId = RouteGroup(id = 2)
val routeGroupWithNameAndId = RouteGroup(id = 2, name = "example")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With