Property delegation in Kotlin

Level 5344 keystrokes

With by, a property hands its get and set to a delegate. Delegates.observable calls a handler after each change, and Delegates.vetoable calls one before the change and only accepts the new value when it returns true, so age = -5 is rejected.

Kotlin code

// Import the standard delegates
1import kotlin.properties.Delegates
2
3class User {
// observable: starts as "Unknown"; the handler gets the property, the old and the new value
4 var name: String by Delegates.observable("Unknown") { _, old, new ->
// Runs after every assignment
5 println("Name: $old -> $new")
6 }
// vetoable: starts at 0; the handler decides whether the new value is accepted
7 var age: Int by Delegates.vetoable(0) { _, _, new ->
// Accept only non-negative values; false keeps the old value
8 new >= 0
9 }
10}
11
// Create a user with the initial values
12val user = User()
// Prints Name: Unknown -> Alice
13user.name = "Alice"
// Prints Name: Alice -> Bob
14user.name = "Bob"
// 25 >= 0, so it is accepted
15user.age = 25
// Rejected: age stays 25
16user.age = -5
// Prints Final: Bob, 25
17println("Final: ${user.name}, ${user.age}")

Output

Name: Unknown -> Alice
Name: Alice -> Bob
Final: Bob, 25
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • .× 10
  • "× 10
  • =× 6
  • ,× 5
  • (× 5
  • )× 5
  • {× 5
  • }× 5
  • -× 4
  • :× 4

More Kotlin examples at level 5

← Kotlin typing practice