Custom Getters and Setters with field
Write computed properties and custom setters using the backing field keyword.
Properties Are Not Just Fields
Each Kotlin property has an auto-generated getter (and for var, a setter). You can override them to add logic — validation, logging, computation.
Custom Getter
Override get() to compute the value each time it is read.
class Circle(val radius: Double) {
val area: Double
get() = Math.PI * radius * radius
}
fun main() {
val c = Circle(3.0)
println(c.area) // ~28.27
}All lessons in this course
- Primary Constructor and Property Parameters
- init Blocks and Initialization Order
- Custom Getters and Setters with field
- lateinit and Lazy Initialization