Delegated Properties
A mechanism that delegates property read/write operations to another object. Use the by keyword to specify a standard delegated property or a custom delegate.
Syntax
// Basic syntax for a delegated property
var propertyName: Type by delegateObject
// Delegated properties from the standard library
import kotlin.properties.Delegates
var propertyName: Type by Delegates.observable(initialValue) { prop, old, new -> }
var propertyName: Type by Delegates.notNull()
Delegate Types
| Delegate | Description |
|---|---|
| by lazy { } | A lazy property that is initialized on first access. |
| Delegates.observable(initialValue) { prop, old, new -> } | Invokes a callback whenever the value changes. Use this to observe property changes. |
| Delegates.vetoable(initialValue) { prop, old, new -> } | Updates the value only when the callback returns true. Use this for validation. |
| Delegates.notNull() | Allows declaration without an initial value, but throws an exception if accessed before initialization. |
Sample Code
import kotlin.properties.Delegates
class User {
// Logs a message whenever the value changes.
var name: String by Delegates.observable("(not set)") { _, old, new ->
println("Name changed: $old → $new")
}
// Updates the value only if the new value is 0 or greater.
var age: Int by Delegates.vetoable(0) { _, _, new ->
new >= 0
}
// Requires initialization before access.
var id: Int by Delegates.notNull()
}
fun main() {
val user = User()
user.id = 1001 // Initializes the notNull property.
user.name = "Alice" // Callback is invoked.
user.name = "Bob" // Callback is invoked again.
user.age = 25
println(user.age) // 25
user.age = -1 // Rejected because the value is negative.
println(user.age) // 25 (unchanged)
}
Details
Delegated properties let you extract property access logic into reusable classes. Simply place a delegate object after the by keyword to handle complex access behavior in a clean, concise way.
Delegates.observable is useful when you want to observe value changes, and Delegates.vetoable is convenient when you need to validate changes before they are applied. To create a custom delegate, implement the ReadWriteProperty<T, V> interface and define both getValue and setValue.
If you find any errors or copyright issues, please contact us.