What are the reason why we use or explicitly use get()
and set()
in Kotlin? I have a model that is throwing an error when I remove explicit get()
in its variable declaration.
data class SampleDomain(
val publishTime: String = ""
) {
// Removing get() here, publishTime becomes empty
val formattedDate: String
get() = LocalDate.parse(publishTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME).format(
DateTimeFormatter.ofPattern("MMM. dd, yyyy")
)
}
get()
and set()
is how we define getters and setters in Kotlin. So simply answering why do we use them is because they are required to define a getter/setter.
If you mean the difference between the following definitions:
val formattedDate: String = acquireDate()
val formattedDate: String get() = acquireDate()
Then get()
is not here just to be more explicit. These two code fragments do much different things. The first acquires the date during the object initialization, stores it inside a field and the getter returns this stored value. The second defines a custom getter, but the value is not stored anywhere - the date is acquired again and again every time the getter is invoked.
See the documentation for more info: https://kotlinlang.org/docs/properties.html#getters-and-setters