Observable properties are a powerful feature in Kotlin that allow you to monitor and react to changes in property values. They provide a clean and efficient way to implement the observer pattern, enabling you to execute custom logic whenever a property's value is modified.
In Kotlin, observable properties are implemented using the Delegates.observable()
function from the standard library. This function creates a property delegate that wraps the actual property value and notifies observers when the value changes.
Here's the basic syntax for creating an observable property:
import kotlin.properties.Delegates
var propertyName: Type by Delegates.observable(initialValue) { property, oldValue, newValue ->
// Observer logic here
}
The observer lambda receives three parameters:
property
: A reference to the property being modifiedoldValue
: The previous value of the propertynewValue
: The new value being assigned to the propertyLet's look at a practical example of using observable properties to monitor temperature changes:
import kotlin.properties.Delegates
class TemperatureSensor {
var temperature: Double by Delegates.observable(0.0) { _, oldValue, newValue ->
println("Temperature changed from $oldValue to $newValue")
if (newValue > 30.0) {
println("Warning: High temperature detected!")
}
}
}
fun main() {
val sensor = TemperatureSensor()
sensor.temperature = 25.5
sensor.temperature = 32.0
}
In this example, we create a TemperatureSensor
class with an observable temperature
property. The observer prints a message whenever the temperature changes and issues a warning if it exceeds 30.0 degrees.
Kotlin also provides Delegates.vetoable()
, which allows you to validate and potentially reject property changes:
import kotlin.properties.Delegates
var age: Int by Delegates.vetoable(0) { _, _, newValue ->
newValue >= 0
}
fun main() {
age = 25 // Allowed
println(age) // Output: 25
age = -5 // Rejected
println(age) // Output: 25 (unchanged)
}
In this example, the age
property only accepts non-negative values. Any attempt to set a negative age is vetoed, and the property retains its previous value.
Observable properties in Kotlin offer a clean and efficient way to implement reactive programming patterns. They enhance code readability and maintainability by centralizing change-related logic. As you continue to explore Kotlin, consider integrating observable properties into your projects for more robust and responsive applications.
For more advanced topics related to properties and delegation in Kotlin, explore Kotlin Extension Properties and Kotlin Delegation Pattern.