Learning Kotlin: The vetoable delegate

Submitted by Robert MacLean on Fri, 08/31/2018 - 09:00
**More Information** * This is the 29th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) * This follows the [introduction to the `by` operator and delegates](/learning-kotlin-by-delegate-properties)

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)

  1. import kotlin.properties.Delegates
  2.  
  3. class User() {
  4.     var age : Int by Delegates.vetoable(0)  { property, oldValue, newValue ->
  5.         newValue > oldValue
  6.     }
  7. }
  8.  
  9. fun main(args:Array<String>) {
  10.     val user = User()
  11.     user.age = 10;
  12.     println(user.age)
  13.  
  14.     user.age = 15
  15.     println(user.age)
  16.  
  17.     user.age = 10
  18.     println(user.age)
  19. }

This produces:

10
15
15