Robert MacLean
31 August 2018
**More Information**
- This is the 29th post in a multipart series.
If you want to read more, see our series index - This follows the introduction to the
by
operator and delegates
The vetoable delegate is usable with variables only (i.e. you need to be able to change the value) and it takes a lambda which returns a boolean. If the return value is true, the value is set; otherwise, the value is not set.
As an example, we will have a User
and ensure the age
can never be lowered (since time only goes forward)
import kotlin.properties.Delegates
class User() {
var age : Int by Delegates.vetoable(0) { property, oldValue, newValue ->
newValue > oldValue
}
}
fun main(args:Array<String>) {
val user = User()
user.age = 10;
println(user.age)
user.age = 15
println(user.age)
user.age = 10
println(user.age)
}
This produces:
10 15 15