Set getter as private in kotlin data class primary constructor

I have a data class which is deserialized using gson (on Android platform). Here is how it looks like:

data class ResponseDto(@SerializedName("something") val something: Something? = null, @SerialziedName("timeStamp") val timeStamp: String? = null) {
...
}

Now I want the “timeStamp” to be accessible with gson (to be de-serialized of course), so I need a public setter, but I don’t want the next developer who works on the app to be confused about the String, so I want a private getter and a manual getter function like this:

fun getTimeStamp(): Instant{
        return Instant.parse(timeStamp)
    }

Wouldn’t it be more convenient to be able to set private getter and/or setter for such scenarios?
Are there any workarounds around this problem?

I don’t know Gson that well, but if it requires a public setter for deserialization, then doesn’t it require a public getter for serialization?

Generally, if you need a property with a different type for getter and setter, then I believe this is not supported. Create two functions or two separate properties.

Speaking about your case specifically, I think it would be the best to have just a timestamp: Instant and either configure Gson somehow so it knows how to serialize/deserialize InstantString or create auxiliary property like: @SerialziedName("timeStamp") timestampAsString: String and make it ignore the first property. Or something similar - again, I don’t know Gson very well.

3 Likes

If you can’t configure Gson, another way around it is to have the primary constructor for your class to have timeStamp as an Instant, then create a secondary constructor that accepts timeStamp as a String, and configure Gson to use the secondary constructor. Then, you can parse the string into an Instant and call the primary constructor.

data class ResponseDto(val something: Something? = null, val timeStamp: Instant? = null) {
    constructor(@SerializedName("something") something: Something? = null, @SerializedName("timeStamp") timeStamp: String? = null) : this(something, timeStamp?.let { Instant.parse(it) })
...
}
3 Likes