In Kotlin, we can declare properties with ‘var‘ and ‘val‘ keywords. ‘var‘ is used for declaring mutable properties and ‘val‘ is used for declaring immutable (read-only) properties. By default, Kotlin generates default getters and setters for these properties. However, we can also define our custom getters and setters (also known as accessors) to manipulate the property data according to our needs.
Custom getters and setters can be declared inside the property header or outside the header. Let’s explore both ways with examples.
### Custom Accessors Inside Property Header
Custom accessors inside the property header can be defined using the ‘get()‘ and ‘set()‘ methods. Here’s an example of using custom accessors inside the property header:
var myName: String = ""
get() = field.toUpperCase()
set(value) {
field = "Hello, $value!"
}
In this example, we have declared a ‘var‘ property named ‘myName‘, which has an initial value of an empty string.
The ‘get()‘ method inside the property header acts as a custom getter for the property ‘myName‘. It returns the ‘field‘ value, which refers to the backing field of the property (i.e., the actual property value). It then applies the ‘toUpperCase()‘ method to the value and returns the final value.
The ‘set()‘ method inside the property header acts as a custom setter for the property ‘myName‘. It takes an input parameter ‘value‘, which will be used to set the ‘field‘ property to a new value. In this example, the ‘field‘ value is set to ‘"Hello, $value!"` which includes the ‘value‘ parameter.
### Custom Accessors Outside Property Header
Custom accessors outside the property header can be defined using the ‘get‘ and ‘set‘ keywords along with the property name. Here’s an example of using custom accessors outside the property header:
var myAge: Int = 0
private set(value) {
field = if (value > 0) value else 0
}
val myFullName: String
get() = "$firstName $lastName"
In this example, we have declared a ‘var‘ property named ‘myAge‘, which has an initial value of ‘0‘.
The ‘set‘ method outside the property header acts as a custom setter for the property ‘myAge‘. We have used the ‘private‘ modifier with the ‘set‘ method to restrict the setter method access from outside the class. The ‘value‘ parameter contains the value to be set. Before setting the ‘field‘ value, we have applied a condition to check if the ‘value‘ parameter is greater than ‘0‘. If the ‘value‘ parameter is greater than ‘0‘, the ‘field‘ value is set to ‘value‘, else the ‘field‘ value is set to ‘0‘.
In this example, we have declared a ‘val‘ property named ‘myFullName‘, which is a read-only property. The ‘get‘ method outside the property header acts as a custom getter for the property ‘myFullName‘. It returns the concatenated full name of ‘firstName‘ and ‘lastName‘.