Learning Kotlin: The vetoable delegate

Note This is the 29th post in a multipart series. If you want to read more, see our series index or this follow-up on the introduction to the by operator and delegates.

The vetoable delegate is usable with variables only (i.e., you must be able to change the value), and it takes a lambda that returns a boolean. If the return value is true, the value is set; otherwise, it is not set.

For example, we’ll ensure a User's age can never decrease—since time only moves 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) // 10
    user.age = 15
    println(user.age) // 15
    user.age = 10
    println(user.age) // 15
}