vetoable
- Kotlin course
- Intermediate
- Lesson 73/116
- 5 min
Learn vetoable properties with vetoable.
vetoable
vetoable lets you reject an assignment to a property based on a condition. Example: var age by Delegates.vetoable(0) { _, _, new -> new >= 0 }. If the lambda returns true the assignment is accepted; if it returns false the assignment is rejected and the value stays unchanged.
This is useful for protecting invariants: age cannot be negative, email cannot be empty and so on. observable accepts every assignment; vetoable validates first. Both come from the Delegates object and use a similar lambda signature.
How vetoable works
The vetoable lambda takes three parameters: the property reference, the old value and the new value. The lambda returns a Boolean. If true the new value is assigned; if false the old value is kept.
Example: var age by Delegates.vetoable(0) { _, _, new -> new >= 0 }. age = 25 is accepted (25 >= 0). age = -5 is rejected (-5 < 0); age stays 25. This is a clean way to protect a business rule in one line. Compare with observable: observable always accepts, vetoable is selective.
Practice Validate age with vetoable
Add import kotlin.properties.Delegates. Define var age by Delegates.vetoable(0) { _, _, new -> new >= 0 }. In main assign age = 25 and call println(age). Then assign age = -5 and call println(age) again.
Starter code
import kotlin.properties.Delegates
// Define age with the vetoable delegate: reject negative values
fun main() {
// Assign 25 and print, then assign -5 and print
}Sample solution
import kotlin.properties.Delegates
var age by Delegates.vetoable(0) { _, _, new -> new >= 0 }
fun main() {
age = 25
println(age)
age = -5
println(age)
}Expected output
25 25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does vetoable do?
- Can reject by condition Correct answer
- Never changes
- Always accepts
- Only reads
Explanation: vetoable rejects the assignment when the lambda returns false.
2 Complete the vetoable declaration
Delegates.____(0) { _, _, new -> new >= 0 }
Delegates.vetoable(0) { _, _, new -> new >= 0 }
Explanation: vetoable rejects negative values.
3 Match the vetoable concepts
| Term | Meaning |
|---|---|
vetoable |
Can reject |
observable |
Tracks |
true |
Accept |
false |
Reject |