0
0
KotlinConceptBeginner · 3 min read

What is Vetoable Property in Kotlin: Explanation and Example

In Kotlin, a 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.

kotlin
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}")
}
Output
Trying to change balance from 0 to 100 Trying to change balance from 100 to -50 Trying to change balance from 100 to 200 Final balance: 200
🎯

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 true or false.
  • Returning false keeps the old value unchanged.
  • Useful for validation and enforcing rules on property changes.

Key Takeaways

A vetoable property lets you control if a new value should replace the old one.
The change handler returns true to accept or false to reject the new value.
Use vetoable properties to enforce rules or validate data before updating.
It simplifies validation logic by embedding it directly in the property.
Rejected changes leave the property value unchanged.