Properties
In this page:
class ClassName {
var property: Type = initialValue
get() = field // custom getter
set(value) { field = value } // custom setter
val computed: Type
get() = expression
}
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
// Define a class `Temperature`
class Temperature(var celsius: Double)
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `temp`, set to `Temperature(20.0)`
val temp = Temperature(20.0)
// Print "Celsius: ${temp.celsius}" to the console, with a trailing newline
println("Celsius: ${temp.celsius}")
temp.celsius = 25.0
// Print "Updated: ${temp.celsius}" to the console, with a trailing newline
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
// Define a class `Rectangle`
class Rectangle(val width: Double, val height: Double) {
val area: Double
get() = width * height
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `rect`, set to `Rectangle(4.0, 5.0)`
val rect = Rectangle(4.0, 5.0)
// Print "Area: ${rect.area}" to the console, with a trailing newline
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.
field refers to the property's backing storage.Example: Custom Setters
// Define a class `Account`
class Account {
// Declare a mutable variable `balance` (a Double), initialized to `0.0`
var balance: Double = 0.0
set(value) {
field = if (value < 0) 0.0 else value
}
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `account`, set to `Account()`
val account = Account()
account.balance = -50.0
// Print "Balance: ${account.balance}" to the console, with a trailing newline
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
// Define a class `Counter`
class Counter {
// Declare a mutable variable `count` (an Int), initialized to `0`
var count: Int = 0
private set
// Define the function `increment` with no parameters
fun increment() {
count++
}
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `counter`, set to `Counter()`
val counter = Counter()
counter.increment()
counter.increment()
// Print "Count: ${counter.count}" to the console, with a trailing newline
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: