What is Vetoable Property in Kotlin: Explanation and Example
vetoable property is a special kind of observable property that allows you to intercept and decide whether a new value should be accepted or rejected before it is set. It uses a handler function that returns true to accept the change or false to veto it, preventing the property from updating.How It Works
Think of a vetoable property like a gatekeeper for a value. When you try to change the property's value, the gatekeeper checks the new value and decides if it should be allowed or not. If the gatekeeper says "yes," the property updates; if "no," the property keeps its old value.
This is done by providing a lambda function that receives the old value and the new value. Inside this function, you write the rules for accepting or rejecting the change. The function returns true to accept or false to reject the new value.
This mechanism is useful when you want to control how a property changes, like preventing invalid data or enforcing limits.
Example
This example shows a vetoable property that only accepts new values if they are positive numbers.
import kotlin.properties.Delegates class Account { var balance: Int by Delegates.vetoable(0) { _, oldValue, newValue -> println("Trying to change balance from $oldValue to $newValue") newValue >= 0 // Accept only if newValue is zero or positive } } fun main() { val account = Account() account.balance = 100 // Accepted account.balance = -50 // Rejected account.balance = 200 // Accepted println("Final balance: ${account.balance}") }
When to Use
Use a vetoable property when you want to control or validate changes to a property before they happen. For example:
- Preventing invalid or out-of-range values in settings or configurations.
- Enforcing business rules, like not allowing a bank account balance to go negative.
- Adding simple validation logic directly in the property without extra setter methods.
This helps keep your code clean and ensures your data stays consistent.
Key Points
- Vetoable properties let you approve or reject value changes.
- The lambda receives old and new values and returns
trueorfalse. - Returning
falsekeeps the old value unchanged. - Useful for validation and enforcing rules on property changes.