I have a data class like so:
data class Session(
val sessionId: String,
val duration: Int,
val creationTimestamp: String, //example: "2021-04-20T15:45:23.160599+00:00"
val status: String
) {
val creationTime: ZonedDateTime
get() {
return ZonedDateTime.parse(creationTimestamp)
}
}
The creation time is a string but I have added a ZonedDateTime property which returns it parsed.
Even though this works, I wanted to find a way to avoid the time getting parse every time it is accessed. So I just wrote
val creationTime: ZonedDateTime = ZonedDateTime.parse(creationTimestamp)
in the hopes that this would run after the data class constructor. Nope.
One. Is there a way to achieve this without making the property nullable like this?
private var creationTime: ZonedDateTime? = null
get() {
if(field == null) {
field = ZonedDateTime.parse(creationTimestamp)
}
return field
}
Two. What is the conventional wisdom on this. Is it good practice to have convenience properties in a data class?