Properties
In this page:
Automatic Getters and Setters
Every val/var property automatically has a getter (and, for var, a setter) generated by the compiler, so you access it directly with object.property instead of calling a method.
Example: Automatic Getters and Setters
class Temperature(var celsius: Double)
fun main() {
val temp = Temperature(20.0)
println("Celsius: ${temp.celsius}")
temp.celsius = 25.0
println("Updated: ${temp.celsius}")
}
Login to try C/C++/Java/PHP code in the editor
Custom Getters
A property can define a custom get() that computes its value from other properties on the fly, rather than storing that value directly.
Example: Custom Getters
class Rectangle(val width: Double, val height: Double) {
val area: Double
get() = width * height
}
fun main() {
val rect = Rectangle(4.0, 5.0)
println("Area: ${rect.area}")
}
Login to try C/C++/Java/PHP code in the editor
Custom Setters
A var property can define a custom set(value) that runs validation or transformation logic every time a new value is assigned.
Note: Inside a custom setter, field refers to the property's backing storage.
Example: Custom Setters
class Account {
var balance: Double = 0.0
set(value) {
field = if (value < 0) 0.0 else value
}
}
fun main() {
val account = Account()
account.balance = -50.0
println("Balance: ${account.balance}")
}
Login to try C/C++/Java/PHP code in the editor
Restricting Setter Visibility
Adding private set after a var property lets other code read it freely while only the class itself can change its value, which is a common way to expose read-only state safely.
Example: Restricting Setter Visibility
class Counter {
var count: Int = 0
private set
fun increment() {
count++
}
}
fun main() {
val counter = Counter()
counter.increment()
counter.increment()
println("Count: ${counter.count}")
}
Login to try C/C++/Java/PHP code in the editor
- Writing manual
getX()/setX()methods out of Java habit, when Kotlin properties already generate them automatically. - Forgetting that a custom getter recomputes its value every time it's accessed, rather than being cached automatically.
- Using
varfor a property that should never change from outside the class, instead ofvalwith a private setter or backing field.
- A property declared with
val/varautomatically gets a generated getter (and setter forvar) behind the scenes. - Custom getters and setters can be written with
get() = ...andset(value) { ... }right after the property declaration. - A custom getter re-evaluates its expression every time the property is read; it is not cached.
private seton avarproperty allows public reads but restricts writes to inside the class.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: