In some situations, we may not want to rely on the default getter/setter that Kotlin provides. In those cases, we can provide our own custom accessors for any of our defined properties. For mutable variables, we can provide both custom getters and setters, while for read-only variables we can only provide a custom getter. To illustrate this, let's start by adding a custom setter for the description property, as follows:
- We'll start with our existing Course class, which exposes a public description property:
class Course(courseTitle: String) {
...
var description = ""
}
- To add a custom getter to the description property, we can then add a set(field) {} block immediately following the definition of description:
class Course(courseTitle: String) {
...
var description = ""
set(value) {
field = value
}
}
Within this block, we can then add any custom logic we want. You'll notice, in this example that we assign value to field. In this case, field is the backing property for our custom setter. Without updating field, the value for description would not be updated.
If we wanted to log the new value when the setter is used, we could add the following line:
class Course(courseTitle: String) {
...
var description = ""
set(value) {
println("description updated to: $value")
field = value
}
}
- Now globally let's add a custom getter as well. The process is very much the same as for the custom setter, except there is no value argument passed in:
class Course(courseTitle: String) {
val title = courseTitle
var description = ""
set(value) {
println("description updated to: $value")
field = value
}
get() {
// add code for getter
return field
}
}
With custom property accessors, we can control and extend the property access behavior of our classes, giving us greater control over how our classes function. In the next section, we'll explore properties that are defined within a class's primary constructor rather than the class body.