Custom Getters / Setters
A mechanism for customizing the behavior when accessing a property with a getter, and defining the behavior when modifying a value with a setter.
Syntax
// Custom getter
val propertyName: Type
get() = expression
// Custom setter (requires var)
var propertyName: Type = initialValue
get() = field
set(value) {
field = value
}
Syntax / Keywords
| Syntax / Keyword | Description |
|---|---|
| get() { } | Defines the logic called when the property is read. |
| set(value) { } | Defines the logic called when a value is assigned to the property. The parameter name is arbitrary. |
| field | A reference to the backing field. Can only be used inside a getter or setter. |
Sample Code
class Circle(val radius: Double) {
// Custom getter: calculates and returns the area.
val area: Double
get() = Math.PI * radius * radius
}
class Person(name: String) {
// Validates the value in the setter.
var name: String = name
set(value) {
// Rejects empty strings.
field = if (value.isNotBlank()) value else field
}
// Custom getter: returns the name converted to uppercase.
val upperName: String
get() = name.uppercase()
}
fun main() {
val circle = Circle(5.0)
println(circle.area) // 78.53...
val person = Person("Tanaka")
println(person.upperName) // TANAKA (converted to uppercase)
person.name = "" // Empty string is ignored.
println(person.name) // Tanaka (unchanged)
person.name = "Suzuki"
println(person.name) // Suzuki
}
Overview
A custom getter lets you compute and return a property's value on every access. Since it requires no backing field, it is useful for expressing values derived from other properties.
In a custom setter, you can validate or transform the new value received via the value parameter before assigning it to field. Never assign directly using the property name inside a setter, as that causes infinite recursion — always use field instead.
If you find any errors or copyright issues, please contact us.